//####### Copyright Mavice LLC 2009 – www.mavice.com ########

var productArr = new Array();
var page = 1;
var numPages = 1;
var pageSize = 20;
var numItems = 0;
var filter = "type";
var filterVal = "CTP";
var orderBy = "added_mall_date";
var gameFilter = "DE";
var department = "CTP";

var totalCost = {};

$(document).ready(function(){

    if($.query.get("department")){
        department = $.query.get("department");
        saveDepartment(department);
    }
    
    var flashvars = {
        contentpath: $("#shopTheMall_flash .srcFile").text(),
        accountId: (accountId ? accountId : 0),
        xmlpath: $("#shopTheMall_flash .xmlFile").text(),
        requestorId: "casual-charmgirlsclub",
        username: ($.cookie("displayName") ? $.cookie("displayName") : 0),
        personaId: (personaId ? personaId : 0),
        ssbase: "/clothing.action?service="
    };
    var params = {
        wmode: "transparent",
        allowFullScreen: "false",
        allowScriptAccess: "always"
    };
    var attributes = {
        name: "flash_swf"
    };

    swfobject.embedSWF("Shell.swf", "flash_swf", "246", "588", "9.0.0.0", "expressInstall.swf", flashvars, params, attributes);

    ///////////// MALL EVENT HANDLERS /////////////

	// Move to previous page
	$('div.mall_upper .page_left').click(function(event) {
	    event.preventDefault();
	    
		if (page > 0){
			page--;
    		loadMallItems();
        }
	});
	
	// Move to next page
	$('div.mall_upper .page_right').click(function(event) {
	    event.preventDefault();
	    
		if (page < numPages){
			page++;
			loadMallItems();			
        }
	});
	
	// Move to a specified page number
	$('div.mall_upper .page_links li a').live('click',function(event) {
	    event.preventDefault();
	    
		var pageLinkClick = parseInt($(this).text());
		if(pageLinkClick != page){
			page = pageLinkClick;
			loadMallItems();
        }
	});

    // 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 .buy_it .login").show()
                $(this).find(".popup .buy_it .buy").hide();
            }
            
            if($(this).children(".locked").text() == "true")
                $(this).find(".popup .buy_it .buy").hide();

            $(this).children('div.popup').show();
        })
        .live('mouseout', function(event){
            $('#load_products li div.popup').hide();
        });

    // Upper rounded box
    $('#load_products li div.try_it_on').live('click',function() {
	    if($(this).children('div.slider').css('margin-top') == '0px'){
	        var self = $(this);
	        
            $("#load_products li div.try_it_on .wearing").hide();
            $("#load_products li div.try_it_on .try").show();
	        
            self.find("div.slider .try").slideUp("fast", function(){
                self.find("div.slider .wearing").slideDown("fast");
            });

	        var product = $(this).closest("li");
	        var itemId = product.children(".itemId").text();
	        var type = product.children(".type").text();
	        var accType = product.children(".accType").text();
	        var image = product.children(".image").text();
	        var price = product.children(".price").text();
	        var locked = product.children(".locked").text();
	        var path = product.find("div.image img").attr("src");
	        
	        var flashObject = document.getElementById("flash_swf");
	        if(flashObject){
			    flashObject.addElement(image, path, type, accType);

			    if(locked == "false")
                    updateClothing(type, accType, price);
            }
	    }
    });

    // Lower rounded box
    $('#load_products li div.buy_it').live('click',function() {
    
        if(!is_logged_in)
            location.href = "login.action";
    
        var self = $(this);
	    var product = $(this).closest("li");
	    var itemId = product.children(".itemId").text();
	    var closetItemId = product.children(".closetItemId").text();
	    var name = product.children(".name").text();
	    var price = product.children(".price").text();
	    var type = product.children(".type").text();
	    var accType = product.children(".accType").text();
	    var color = product.children(".color").text();
	    var eaItem = product.children(".eaItem").text();
	    var locked = product.children(".locked").text();

        if(locked == "true")
            return;

        if(accType == "")
            accType = "NA";

        var url = "";
        var data = {}
        if(eaItem == "true"){
		    url = "ss.action?service=/v2/m1/xml/casual/charmgirls/mall/buyEaFashion&template=setWithStatus&noflash=1"+getCredentials();
            data = {
	            eaItemId: itemId,
	            price: price,
	            name: name,
	            type: type,
	            color: color,
	            accType: accType
            };
        }
        else{
		    url = "ss.action?service=/v2/m1/xml/casual/charmgirls/mall/buyUserFashion&template=setWithStatus&noflash=1"+getCredentials();
            data = {
	            itemId: closetItemId,
	            price: price
            };	            
        }
  
	    $.ajax({
	        url: url,
	        type: "POST",
	        dataType: "xml",
	        data: data,
	        success: function(data, textStatus){
                self.find("div.slider .buy").slideUp("fast", function(){
                    if(sharedServicesSuccess(data)){
                        self.find("div.slider .purchased").slideDown();
                        product.find(".icons .purchased").show();
                    }
                    else{
                        self.find("div.slider .insufficient").slideDown();
                    }
                });
	        }
	    });
    });
    
	///////////// SORTING OPTIONS /////////////
	$("#sort_options li:first input").attr("checked", "true");
	$("#sort_options li input").click(function() {
		orderBy = $(this).attr("id").replace("sort_", "");
		page = 1;
		loadMallItems();
	});

	///////////// CONTENT FILTER /////////////
	$("#game_filter li:first input").attr("checked", "true");	
	$("#game_filter li input").click(function() {
        gameFilter = $(this).attr("value");
        
        if(gameFilter == "UGC")
            saveDepartment("none");
        
        $.cookie("gameUnlocked_"+gameFilter, "");
        var self = this;
        setTimeout(function(){
            $(self).siblings("label").children("span").fadeOut();
        }, 3000);
		page = 1;
		loadMallItems();
	});
	
	///////////// DEPARTMENT FILTER /////////////
    saveDepartment(department);
	$("#department_filter li a").click(function(event){
	    event.preventDefault();
 
	    var id = $(this).attr("id").replace("department_", "");
        saveDepartment(id);
        loadMallItems();
	});

    // Message bar showing
    if($.cookie('messageBarHide_ShoppingMall') != '1'){
        $("#mallContainer .message_bar:first")
            .slideDown(400);
    }

    loadMallItems();
});

function saveDepartment(id){
    $("#mallBannerSpot").hide();
    var banner = $("#department_"+id).siblings("span.banner").html();
    $("#mallBannerSpot")
        .html(banner)
        .show();

    filter = "type";
    filterVal = id;
    if(id == "none" || id == ""){
        filter = "";
        filterVal = "";
    }
	page = 1;

    $("#department_filter li a").removeClass("on");
    $("#department_"+id).addClass("on");
}

function loadMallItems(){
    
    var url = "clothing.action?service=/v2/m1/xml/casual/charmgirls/mall/getFashions&template=getMallItems&noflash=1&referer=shopTheMall&pageNum="+page+"&pageSize="+pageSize+"&orderBy="+orderBy+getCredentials();
    if(filter != "")
        url += "&" + filter + "=" + filterVal;

    if(gameFilter != "")
        url += "&gameFilter=" + gameFilter;
    
    $("#products_container").slideUp("fast", function(){
        $("#productsLoading").html(ajaxLoading());
    });
    $.get(url, {}, function(data, textStatus) {

        $("#load_products").html($(data).find("#load_products").html());
        
        numItems = parseInt($(data).find("#_totalResults").text());
        numPages = parseInt($(data).find("#_numPages").text());
        
        $("#productsLoading").html("");
        $("#mallContainer").show();
        $("#products_container").slideDown("fast");

	    updatePagination();
	    
	    if($.cookie("mbHide_messageBar_"+gameFilter) == null){
	        if($("#messageBar_"+gameFilter).size() > 0){
	            $("#mallContainer div.message_bar:visible").hide();
	            $("#messageBar_"+gameFilter).show();
	        }
        }

	    $("#game_filter li input").each(function(){
	        var id = $(this).attr("id").split("_")[1];
	        if($.cookie("gameUnlocked_" + id)){
	            $(this).siblings("label").children("span").show();
            }
	    });
        
        $('#mallContainer .message_bar a.close').click(function() {
            $(this).parent().hide('fast');
            $.cookie('mbHide_'+$(this).parent().attr("id"),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 updateClothing(type, accType, price){
	totalCost[type+accType] = price;
    var total = 0;
	for(var key in totalCost)
	    total += parseInt(totalCost[key]);

	$("#currentOutfitCost .total").text(total);
}

function clearClothing(){
    totalCost = {};
    $("#currentOutfitCost .total").text(0);    
}
