var productArr = new Array();
var page = 1;
var pageSize = 20;
var numItems = 0;
var numPages = 1;
var orderBy = "added_gallery_date";

var reportAbuseItemId = null;

$(document).ready(function(){

    ///////////// SIDEBAR SHARED SERVICE CALLS /////////////

    $.get("ss.action?service=/v2/m1/xml/casual/charmgirls/gallery/getTop3ItemDesigner&template=getDesignerOfTheDay&noflash=1&referer=fashion"+getCredentials(), {}, function(data, textStatus){
        $("#widget-designerOfTheDay").html($(data).find("#widget-designerOfTheDay"));
    }, "html");

    $.get("ss.action?service=/v2/m1/xml/casual/charmgirls/mall/getTopDesigners&template=getTopDesigners&noflash=1&referer=fashion"+getCredentials(), {}, function(data, textStatus){
        $("#widget-topDesigners").html($(data).find("#widget-topDesigners"));
    }, "html");


	///////////// DESIGNER OF THE DAY HANDLERS /////////////
/*	
	setTimeout(function() {
		slideContents('right','#dotd_slider','div.designer');
	},500);
	$('#dotd_page_left').click(function() {
		slideContents('left','#dotd_slider','div.designer');
		return false;
	});
	$('#dotd_page_right').click(function() {
		slideContents('right','#dotd_slider','div.designer');
		return false;
	});
*/
    ///////////// GALLERY EVENT HANDLERS /////////////

	// Move to previous page
	$('div.mall_upper .page_left').click(function(event){
	    event.preventDefault();
	    
		if (page > 0){
			page--;
    		loadGalleryItems();
        }
	});
	
	// Move to next page
	$('div.mall_upper .page_right').click(function(event){
	    event.preventDefault();
	    ;
		if (page < numPages){
			page++;
			loadGalleryItems();			
        }
	});

	// Move to a specified page number
	$('div.mall_upper .page_links li a').live('click',function(event){
	    event.preventDefault();
	    
		var pageLinkClick = $(this).text();
		if(pageLinkClick != page){
			page = parseInt(pageLinkClick);
			loadGalleryItems();
        }
	});

    // Popup rounded box on click
    $("#load_products li")
        .live('mouseover', function(event){
            event.stopPropagation();
            
            $('#load_products li div.popup').hide();

            if(!is_logged_in){
                $(this).find(".popup .login").show()
                $(this).find(".popup .like_this").hide();
            }
                            
            $(this).children('div.popup').show();
        })
        .live('mouseout', function(event){
            $('#load_products li div.popup').hide();
        });

    // Lower rounded box
    $("#load_products li div.popup .try_it_on").live('click',function(event) {
    
        if(!is_logged_in)
            location.href = "login.action";
    
        var self = $(this);
        var product = $(this).closest("li");
        var closetItemId = product.children(".closetItemId").text();
        var voted = product.children(".voted").text();

        if(voted == "false"){
            $.get("ss.action?service=/v2/m1/xml/casual/charmgirls/gallery/voteForGalleryItem&template=setWithStatus&noflash=1&itemId="+closetItemId+getCredentials(), {}, function(data, textStatus){
                if(sharedServicesSuccess(data)){
                    // Increment the number of likes immediately
                    var numLikesEl = product.find(".buy_it .likes .numLikes");
                    var numLikes = parseInt(numLikesEl.text());
                    if(!numLikes || numLikes == "NaN")
                        numLikes = 0;
                    numLikes++;
                    numLikesEl.text(numLikes);
                
                    // animate the likethis -> liked transition
                    self.find(".like_this").slideUp("fast", function(){
                        product.find(".icons .liked").show();
                        $(this).siblings(".liked").slideDown("fast");
                    });        

                    awardUser("fashions_like", function(data){
                        var msg = $(data).find("root message").text();
                        var charm = $(data).find("root charms item[1] assets[size='1'] BAS").text();

                        showAdjustedAwardPopup(msg, charm, event);
                    });
                }
            }, "xml");
        }
    });

    if(is_logged_in){
    
        ///////// REPORT ABUSE HANDLERS //////////
        $('#load_products li .reportAbuse').live('click',function(event){
            event.preventDefault();

            $("#abuser").html($(this).closest("li").children(".designer").text());
            $("#reporter").html(personaName);
            $('#reportAbusePopup')
                .css("left", (event.pageX-240)+"px")
                .css("top", (event.pageY-400)+"px");
            
            reportAbuseItemId = $(this).closest("li").children(".closetItemId").text();
            $('#reportAbusePopup').show();
        });
        
        $('#reportAbusePopupClose, #reportAbuseCancelButton').live('click',function() {
            resetReportAbuse();
            return false;
        });
         
        $("#reportAbuseSubmitButton").live('click',function(event){
            event.preventDefault();

            var submit = true;
            if($("#violationType").val() == ""){
                submit = false;
                $('#reportAbuseResponse').html($('#reportAbuseViolationReq').html());
            }
            if($("#violationComments").val() == ""){
                submit = false;
                $('#reportAbuseResponse').html($('#reportAbuseCommentReq').html());
            }        
            
            if(!submit)
                return;

            $.ajax({
                url: "ss.action?service=/v2/m1/xml/casual/charmgirls/gallery/flagGalleryItemAsInappropriate&template=setWithStatus&referer=profile&noflash=1"+getCredentials(),
                type: "POST",
                dataType: "xml",
                data: {
                    complaintType: $("#violationType").val(),
                    itemId: reportAbuseItemId,
                    comment: ($("#violationComments").val() ? $("#violationComments").val() : " ")
                },
                success: function(data, textStatus){
                    if(sharedServicesSuccess(data)){
                        $('#reportAbuseResponse').html($('#reportAbuseSubmitted').html());
                        setTimeout(function() {
                            resetReportAbuse();
                        },500);
                    }
                    else{
                        $('#reportAbuseResponse').html(closeButton);
                    }
                }
            });
        });
    }
	
	///////////// SORTING OPTIONS /////////////
	$("#sort_options li:first input").attr("checked", "true");
	$("#sort_options li input").click(function() {
		orderBy = $(this).attr("id").replace("sort_", "");
		page = 1;
		loadGalleryItems();
	});
	
	///////////// ADVERTISEMENTS /////////////
	/*
	$('div.fashion_ad .page_links2 .page_left').click(function() {
		slideContents('left','div.banner_slider','img.banner_ad','.page_links2');
		setTimeout(function() {
			updatePageLinkOnstate('div.banner_slider','img.banner_ad','.page_links2');
		},450);
		return false;
	});
	$('div.fashion_ad .page_links2 .page_right').click(function() {
		slideContents('right','div.banner_slider','img.banner_ad','.page_links2');
		setTimeout(function() {
			updatePageLinkOnstate('div.banner_slider','img.banner_ad','.page_links2');
		},450);
		return false;
	});
	$('div.fashion_ad .page_links2 li.page_link a').click(function() {
		var pageLinkClick = $('div.fashion_ad .page_links2 li a').index(this) - 1;
		updatePageLinks('div.banner_slider','img.banner_ad','.page_links2',pageLinkClick);
		return false;
	});
	$('div.fashion_ad .page_links2 img.page_left_on').fadeOut('fast');
	*/
	$('div.mall_upper .page_left img.page_left_on').fadeOut('fast');
	
	loadGalleryItems();
	
    // Message bar showing
    if($.cookie('messageBarHide') != '1')
	 {
		 $('#mallContainer div.message_bar:first').slideDown(400);
	 }
});

function loadGalleryItems(){
    $("#products_container").slideUp("fast", function(){
        $("#productsLoading").html(ajaxLoading());
    });
    $.get("ss.action?service=/v2/m1/xml/casual/charmgirls/gallery/getGalleryItems&template=getGalleryItems&noflash=1&referer=fashion&pageNum="+page+"&pageSize="+pageSize+"&orderBy="+orderBy+getCredentials(), {}, function(data, textStatus) {
        $("#load_products").html($(data).find("#load_products").html());

        numItems = parseInt($(data).find("#_totalResults").text());
        numPages = parseInt($(data).find("#_numPages").text());

        if(!is_logged_in)
            $("#load_products li .reportAbuse").hide();
        
        if(numItems == 0){
            $("#mall_window .clothing").hide();
            $("#mall_window .no_results").show();
        }
        else{
            $("#mall_window .no_results").hide();
            $("#mall_window .clothing").show();
        }
        
        $("#productsLoading").html("");
        $("#mallContainer").show();
        $("#products_container").slideDown("fast");

	    updatePagination();

        $('#mallContainer .message_bar a.close').click(function() {
	        $(this).parent().hide('fast');
			  $.cookie('messageBarHide',1);
	        return false;
        });
    }, "html");
}

function updatePagination(){
    var adjacents = 4;
    var adjacentsAdd = 0;
    
    var left_add = (adjacents - (numPages-page));
    if(left_add < 0)
        left_add = 0;

    var buildNewPageLinks = "";        
    for(var i=adjacents+left_add; i>0; i--){
        if(page-i > 0)
            buildNewPageLinks += "<li><a href=\"#\">" + (page-i) + "</a></li>";
        else
            adjacentsAdd++;
    }

    buildNewPageLinks += "<li class=\"onstate\"><a href=\"#\">" + page + "</a></li>";
    for(var i=page+1; i<=page+adjacents+adjacentsAdd; i++){
        if(i <= numPages)
            buildNewPageLinks += "<li><a href=\"#\">" + i + "</a></li>";
    }
    $('div.mall_upper ul.page_links').html(buildNewPageLinks);
    
    if(numPages <= 1){
        $('div.mall_upper .mall_upper_left .pagination').hide();
    }
    else{
        $('div.mall_upper .mall_upper_left .pagination').show();

        if(page <= 1){
		    $('div.mall_upper a.page_left .page_left_on').hide();
		    $('div.mall_upper a.page_left .page_left_off').show();
        }
        else{
		    $('div.mall_upper a.page_left .page_left_off').hide();
		    $('div.mall_upper a.page_left .page_left_on').show();
        }
        
        if(page < numPages){
		    $('div.mall_upper a.page_right .page_right_off').hide();
		    $('div.mall_upper a.page_right .page_right_on').show();
        }
        else{
		    $('div.mall_upper a.page_right .page_right_on').hide();
		    $('div.mall_upper a.page_right .page_right_off').show();
        }
    }
}

function resetReportAbuse(){
    $('#reportAbusePopup').slideUp("fast",function() {
        $('#violationComments').val('');
        $('#violationType option:first').attr('selected','selected');
        $('#reportAbuseResponse').html('');
    });
}
