﻿
var ChooseDesign = new Object();
var CD = new Object();

CD.a = new Array();
ChooseDesign.first = true;
ChooseDesign.currentCategoryId = 0;
ChooseDesign.fullTemplateArray = new Array();
ChooseDesign.currentPage = 1;
ChooseDesign.imagesFirstPage = 6;
ChooseDesign.imagesPerPage = 9;
ChooseDesign.currentBanners = new Array();
ChooseDesign.fullBannerArray = new Array();

ChooseDesign.splashImageElement = null;
ChooseDesign.ExistingQuerystringVariables = "";
ChooseDesign.SearchResult = "";
ChooseDesign.nextStepPage = "";
ChooseDesign.templateImageRootPath = "";
ChooseDesign.UrlPrefix = "";
ChooseDesign.CategoryName = "";

ChooseDesign.PopularitySort = "popularity";
ChooseDesign.DesignNumberSort = "designnumber";
ChooseDesign.MostCurrentSort = "mostcurrent";
ChooseDesign.RankSort = "rank";
ChooseDesign.CurrentSortByOption = ChooseDesign.RankSort;

ChooseDesign.FormInitFunction = null;


$(document).ready(function() {
    if (ChooseDesign.FormInitFunction !== undefined && ChooseDesign.FormInitFunction !== null)
        ChooseDesign.FormInitFunction();
    
    if (ChooseDesign.SearchResult.length > 0) {
        Designs_DisplaySearchResult();
    }
    else {
        if (ChooseDesign.splashImageElement != null)
            ChooseDesign.splashImageElement.show();
    }
});


function Designs_DisplaySearchResult() {
    var content = "";
    if (ChooseDesign.SearchResult == "none") {
        content = "<span class=\"designCode\">No search results found.</span>"
    }
    else if (ChooseDesign.SearchResult.substring(0, 4) == "full") {//switch the category to this ID
        var switchId = ChooseDesign.SearchResult.substring(4, ChooseDesign.SearchResult.length);
        Designs_ChangeCategory(parseInt(switchId), '');
        return;
    }
    else {//assume it is a real record
        var largeImageSrc = Designs_GetDesignLargeImagePathFromData(ChooseDesign.SearchResult);
        var queryStringOptions = Designs_GetQueryStringOfDataAndExisting(ChooseDesign.SearchResult);
        //content = content + "<td class=\"designImageCell\">";
        content = content + "<a href=\"" + queryStringOptions + "\">";
        content = content + "<img src=\"" + largeImageSrc + "\" class=\"designsImage\" />";
        content = content + "</a><br/>";
        content = content + "<div class=\"designCode\">" + Designs_GetDesignCodeFromData(ChooseDesign.SearchResult) + "</div>";
        if (Designs_GetDesignIsTopSellerFromData(ChooseDesign.SearchResult))
            content = content + "<div class=\"designTopSeller\">[top seller]</div>";
    }
    
    $("#searchResults").html(content);
    $("#searchResults").show();
}

function Designs_HideSearchResult() {
    $("#searchResults").hide();
}


function Designs_ChangeCategory(categoryId, categoryName) {
//    Designs_ResetAllToLoading();
    if (ChooseDesign.first)
        Designs_ToggleFormToShowDesigns();
    
    $("#TitleDiv").html("&nbsp;");
    if (ChooseDesign.fullTemplateArray[categoryId] === undefined) {
        Designs_RequestTemplatesForCategory(categoryId);
    }
    else {
        ChooseDesign.currentCategoryId = categoryId;
        if (ChooseDesign.currentCategoryId == ChooseDesign.AnyClubCategoryId)
            Designs_FlipToPage(1);
        else
            Designs_FlipToPage('viewall');
    }
    if (ChooseDesign.fullTemplateArray[categoryId] === undefined) {
        Designs_RequestBannersForCategory(categoryId);
    }
    else {
        Designs_DisplayBanners();
    }
    ChooseDesign.CategoryName = categoryName;
}

function Designs_RequestTemplatesForCategory(categoryId) {
    ChooseDesign.currentCategoryId = categoryId;
    $.ajax({
        type: "POST",
        url: "DesignsAllInOne.aspx/GetTemplateDataForCategory",
        cache: false,
        data: "{categoryId:" + categoryId + ", rid:" + Math.random() + "}", //rid is just a random number to prevent IE caching (though the POST should ensure that doesn't happen)
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        
        success: Designs_SuccessWithTemplateData
    });
}

function Designs_SuccessWithTemplateData(data) {
    eval(data.d);
    if (ChooseDesign.currentCategoryId == ChooseDesign.AnyClubCategoryId)
        Designs_FlipToPage(1);
    else
        Designs_FlipToPage('viewall');
}

function Designs_RequestBannersForCategory(categoryId) {
    ChooseDesign.currentCategoryId = categoryId;
    $.ajax({
        type: "POST",
        url: "DesignsAllInOne.aspx/GetBannerDataForCategory",
        cache: false,
        data: "{categoryId:" + categoryId + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        
        success: Designs_SuccessWithBannerData
    });
}

function Designs_SuccessWithBannerData(data) {
    eval(data.d);
    Designs_DisplayBanners();
}

function Designs_DisplayBanners() {
    var bannerData = ChooseDesign.fullBannerArray[ChooseDesign.currentCategoryId];
    
    if ((!IsCurrentlyViewingAll() && ChooseDesign.currentPage != 1) || bannerData === undefined || bannerData.length == 0) {
        Designs_HideBanners();
    }
    else {
        var content = "";
        for (var i=0; i < bannerData.length; ++i) {
            content = content + "<div><img src=\"" + bannerData[i] + "\" width=\"645\" height=\"291\" /></div>";
        }
        
        $("#bannerImages").html(content);
        $("#bannerImages").show();
        $('#bannerImages').cycle();
    }
}

function Designs_HideBanners() {
    $('#bannerImages').cycle('destroy');
    $("#bannerImages").html("");
    $("#bannerImages").hide();
}


function Designs_FlipToPage(page) {
//    Designs_ResetAllToLoading();
	if (page == 'next')
		page = Math.min(ChooseDesign.currentPage + 1, ChooseDesign.maxPages);
	if (page == 'previous')
		page = Math.max(ChooseDesign.currentPage - 1, 1);
	
    if (IsCurrentlyViewingAll() && page != 'viewall')
        Designs_TurnOffViewAll();
    if (ChooseDesign.currentPage == 1 && page != 1)
        Designs_HideBanners();
    
    var templateArray = ChooseDesign.fullTemplateArray[ChooseDesign.currentCategoryId];
    ReorderTemplateList(templateArray); // new sorting mechanism call
    
    ChooseDesign.currentPage = page;
    if (page == 1 || IsCurrentlyViewingAll()) {
        Designs_DisplayBanners();
        $("#lastDesignRow").hide();
        $("#TitleDiv").html("&nbsp;");
    }
    else {
        $("#lastDesignRow").show();
        $("#TitleDiv").html(ChooseDesign.CategoryName);
    }
    Designs_AdjustPagingToCurrentPage(templateArray);
    
    if (IsCurrentlyViewingAll()) {
        Designs_ViewAll(templateArray);
    }
    else {
        var baseIndex;
        if ((page - 1) == 0)
            baseIndex = 0;
        else {
            baseIndex = ChooseDesign.imagesFirstPage;
            baseIndex = baseIndex + ((page - 2) * ChooseDesign.imagesPerPage);
        }
        for (var i = 1; i <= ChooseDesign.imagesPerPage; ++i) {
            if (page == 1 && i > ChooseDesign.imagesFirstPage)
                Designs_DisplayTemplate(i, baseIndex, null)
            else
                Designs_DisplayTemplate(i, baseIndex, templateArray);
        }
        Paging_FlipToPage(page);
    }
}


function Designs_DisplayTemplate(imageIndex, baseIndex, templateArray) {
    var arrayIndex = baseIndex + (imageIndex - 1);
    var thisData;
    if (templateArray != null && templateArray[arrayIndex] !== undefined) {
        thisData = templateArray[arrayIndex];
        Designs_SetImage("designImage" + (imageIndex), Designs_GetDesignLargeImagePathFromData(thisData), 'large');
        $("#imageText" + (imageIndex)).html(Designs_GetDesignCodeFromData(thisData));
        if (Designs_GetDesignIsTopSellerFromData(thisData) === true)
            $("#topSeller" + (imageIndex)).html("[top seller]");
        else
            $("#topSeller" + (imageIndex)).html("");
        $("#designImageLink" + (imageIndex)).attr("href", Designs_GetQueryStringOfDataAndExisting(thisData));
        
        $("#designImage" + (imageIndex)).attr('class','designsImage');
        $("#designImage" + (imageIndex)).show();
        $("#imageText" + (imageIndex)).show();
        $("#topSeller" + (imageIndex)).show();
    }
    else {
        Designs_SetImage("designImage" + (imageIndex), "images/dot.gif", 'large');
        $("#designImage" + (imageIndex)).attr('class','blankImage');
        $("#designImageLink" + (imageIndex)).attr("href", "#");
        $("#designImage" + (imageIndex)).hide();
        $("#imageText" + (imageIndex)).hide();
        $("#topSeller" + (imageIndex)).hide();
    }
}

function Designs_ToggleFormToShowDesigns() {
    ChooseDesign.splashImageElement.hide(); //ChooseDesign.splashImageElement is defined and set in the main control
    $("#searchResults").hide();
    for (var i=1; i <= ChooseDesign.imagesPerPage; ++i) {
        $("#designImage" + i.toString()).show();
    }
    $("#templateDisplayTable").show();
    //$("#TitleDiv").html("&nbsp;");
    //$("#TitleDiv").show();
    $("#sortByCellDiv").show();
    
    ChooseDesign.first = false;
}

function Designs_ResetAllToLoading() {
    var src = "App_Themes/Shared/ajax-loading-graphics/dots64.gif";
    
    for (var i=1; i <= ChooseDesign.imagesPerPage; ++i) {
        Designs_SetImage("designImage" + i.toString(), src, 'small');
    }
}

function Designs_SetImage(imageTagId, imageSrc, size) {
    var width = 1, height = 1;
    if (size == 'large') {
        width = height = 204;
    }
    else if (size == 'small') {
        width = 64;
        height = 21;
    }
    var imageObject = $("#" + imageTagId);
    imageObject.attr("height", height);
    imageObject.attr("width", width);
    imageObject.attr("src", imageSrc);
}

function Designs_TurnOffViewAll() {
    $("#ViewAllDiv").hide();
    $(".designPaging").show();
    $("#templateDisplayTable").show();
    $("#ViewAllDiv").html("");
}

function Designs_ViewAll(templateArray) {
    var content = "";
    content = "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" id=\"viewAllTable\">";
    for (var i=0; i < templateArray.length; ++i) {
        if (i % 3 == 0) {
            content = content + "</tr><tr>";
        }
        var largeImageSrc = Designs_GetDesignLargeImagePathFromData(templateArray[i]);
        var queryStringOptions = Designs_GetQueryStringOfDataAndExisting(templateArray[i]);
        content = content + "<td class=\"designImageCell\">";
        content = content + "<a href=\"" + queryStringOptions + "\">";
        content = content + "<img src=\"" + largeImageSrc + "\" class=\"designsImage\" />";
        content = content + "</a><br/>";
        content = content + "<div class=\"designCode\">" + Designs_GetDesignCodeFromData(templateArray[i]) + "</div>";
        if (Designs_GetDesignIsTopSellerFromData(templateArray[i]))
            content = content + "<div class=\"designTopSeller\">[top seller]</div>";
        //content = content + " " + Designs_GetDesignSellQuantityFromData(templateArray[i]);
        content = content + "</td>";
    }
    content = content + "</table>";
    $("#templateDisplayTable").hide();
    $(".designPaging").hide();
    $("#ViewAllDiv").html(content);
    $("#ViewAllDiv").show();
}


function ReorderTemplateList(tList) {
    if (ChooseDesign.CurrentSortByOption == ChooseDesign.PopularitySort)
        sortItemArray(tList, true, Designs_GetDesignSellQuantityFromData, true);
    else if (ChooseDesign.CurrentSortByOption == ChooseDesign.MostCurrentSort)
        sortItemArray(tList, true, Designs_GetDesignIdFromData, true);
    else if (ChooseDesign.CurrentSortByOption == ChooseDesign.DesignNumberSort)
        sortItemArray(tList, false, Designs_GetDesignCodeForSorting, true);
    else if (ChooseDesign.CurrentSortByOption == ChooseDesign.RankSort)
        sortItemArray(tList, false, Designs_GetRankFromData, true);
}

function SetNewOrdering() {
    ChooseDesign.CurrentSortByOption = $("#ddlSortBy").val();
    Designs_ChangeCategory(ChooseDesign.currentCategoryId, "");
}

//AnyClubTemplateArray[10] = "M2116::resources/templates/IM2116/im2116TN.jpg::TemplateID=ZroShOAkBWC2a2%2baCgc79Q%3d%3d::resources/templates/IM2116/im2116PV.jpg::true::145::4";
//splitData[DesignCodeIndex], splitData[DesignSmallImagePathIndex], splitData[TemplateQueryStringIndex], splitData[DesignLargeImagePathIndex]
//M224::orXpCf3JFO9sBs4CDDRvzQ%3d%3d::224/im224dramaPV_204.jpg::false::0::791::100

ChooseDesign.DesignCodeIndex = 0;
ChooseDesign.TemplateQueryStringIndex = 1;
ChooseDesign.DesignLargeImagePathIndex = 2;
ChooseDesign.DesignIsTopSellerIndex = 3;
ChooseDesign.DesignSellQuantityIndex = 4;
ChooseDesign.DesignIdIndex = 5;
ChooseDesign.RankIndex = 6;

function Designs_GetDesignCodeFromData(data) {
    var splitData = data.split("::");
    return splitData[ChooseDesign.DesignCodeIndex];
}

function Designs_GetDesignLargeImagePathFromData(data) {
    var splitData = data.split("::");
    return ChooseDesign.templateImageRootPath + splitData[ChooseDesign.DesignLargeImagePathIndex];
}

function Designs_GetDesignTemplateQueryStringFromData(data) {
    var splitData = data.split("::");
    return splitData[ChooseDesign.TemplateQueryStringIndex];
}

function Designs_GetDesignIsTopSellerFromData(data) {
    var splitData = data.split("::");
    return splitData[ChooseDesign.DesignIsTopSellerIndex] == "true" ? true : false;
}

function Designs_GetDesignSellQuantityFromData(data) {
    var splitData = data.split("::");
    return splitData[ChooseDesign.DesignSellQuantityIndex];
}

function Designs_GetDesignIdFromData(data) {
    var splitData = data.split("::");
    return splitData[ChooseDesign.DesignIdIndex];
}

function Designs_GetRankFromData(data) {
    var splitData = data.split("::");
    return splitData[ChooseDesign.RankIndex];
}


function Designs_GetQueryStringOfDataAndExisting(data) {
    return ChooseDesign.UrlPrefix + ChooseDesign.nextStepPage + "?TemplateID=" + Designs_GetDesignTemplateQueryStringFromData(data) + "&" + ChooseDesign.ExistingQuerystringVariables;
}


function Designs_GetDesignCodeForSorting(data) {
    return stripToNumbersOnly(Designs_GetDesignCodeFromData(data));
}

function stripToNumbersOnly(s) {
    filteredValues = "1234567890.";     // Characters stripped out
    var i;
    var returnString = "";
    for (i = 0; i < s.length; i++) {  // Search through string and append to unfiltered values to returnString.
        var c = s.charAt(i);
        if (filteredValues.indexOf(c) > -1)
            returnString += c;
    }
    return returnString;
}


function Designs_AdjustPagingToCurrentPage(templateArray) {
    var content = "";
    if (templateArray === undefined)
        return;
    var numberOfPages = Math.ceil((templateArray.length - ChooseDesign.imagesFirstPage) / (ChooseDesign.imagesPerPage * 1.0));
    if (numberOfPages * ChooseDesign.imagesPerPage < templateArray.length - ChooseDesign.imagesFirstPage)
        numberOfPages = numberOfPages + 1;
    numberOfPages = numberOfPages + 1;
    
    //set the last page span
    if (numberOfPages > 1) {
        $("#lastPageIndex").html(String.format(ChooseDesign.navItemTemplate, "pageNavItem" + (numberOfPages), numberOfPages, "pageNavItem"));
        $("#lastPageIndex-2").html(String.format(ChooseDesign.navItemTemplate, "pageNavItem" + (numberOfPages) + "-2", numberOfPages, "pageNavItem"));
        $("#lastPageIndex").show();
        $("#lastPageIndex-2").show();
    } else {
        $("#lastPageIndex").hide();
        $("#lastPageIndex-2").hide();
    }
    
    ChooseDesign.currentDisplayStartIndex = 1;
    ChooseDesign.maxPages = numberOfPages;
    ForceUpdateShownPages();
}


function UpdateShownPages() {
	if (ChooseDesign.currentPage > ChooseDesign.currentDisplayStartIndex + 4 || ChooseDesign.currentPage < ChooseDesign.currentDisplayStartIndex) {
		ChooseDesign.currentDisplayStartIndex = ChooseDesign.currentPage;
		ForceUpdateShownPages();
	}
}

function GetStartLowPage() {
	return Math.max(1, Math.min(ChooseDesign.currentDisplayStartIndex, ChooseDesign.maxPages - ChooseDesign.numberPageNumbers));
}

function GetEndHighPage() {
	return Math.min(ChooseDesign.maxPages, ChooseDesign.currentDisplayStartIndex + ChooseDesign.numberPageNumbers) + (ChooseDesign.currentDisplayStartIndex == 1 ? 1 : 0);
}

ChooseDesign.navItemTemplate = "<span id='{0}' class='{2}'><a href='javascript:Designs_FlipToPage({1});'>{1}</a></span>&nbsp;";
function ForceUpdateShownPages() {
	var content = "";
	var content2 = "";
	var style = "pageNavItem";
	for (var p = GetStartLowPage(); p < GetEndHighPage(); ++p) {
		if (p == 1 || p == ChooseDesign.maxPages)
			continue;
		if (p == ChooseDesign.currentPage)
			style = "selectedNavItem";
		else
			style = "pageNavItem";
		content = content + String.format(ChooseDesign.navItemTemplate, "pageNavItem" + (p), p, style);
		content2 = content2 + String.format(ChooseDesign.navItemTemplate, "pageNavItem" + (p) + "-2", p, style);
	}
	ChooseDesign.pagingCycle.html(content);
	ChooseDesign.pagingCycle2.html(content2);
	
	if (ChooseDesign.currentDisplayStartIndex == 1)
		TogglePreDots(false);
	else
		TogglePreDots(true);
	if (ChooseDesign.currentDisplayStartIndex >= ChooseDesign.maxPages - ChooseDesign.numberPageNumbers)
		TogglePostDots(false);
	else
		TogglePostDots(true);
	
	$("#PagingDiv").show();
	$("#PagingDiv-2").show();
}


ChooseDesign.pagingCycle;
ChooseDesign.pagingCycle2;
ChooseDesign.currentDisplayStartIndex = 1;
ChooseDesign.maxPages;
ChooseDesign.numberPageNumbers = 5;

$(document).ready(function() {
	ChooseDesign.pagingCycle = $("#pagingCycle");
	ChooseDesign.pagingCycle2 = $("#pagingCycle-2");
	$("#PREdotdotdot").click(ShowFiveLessPRE);
	$("#POSTdotdotdot").click(ShowFiveMorePOST);
	$("#PREdotdotdot-2").click(ShowFiveLessPRE);
	$("#POSTdotdotdot-2").click(ShowFiveMorePOST);
});

function TogglePreDots(status) {
	if (status) {
		$("#PREdotdotdot").show();
		$("#PREdotdotdot-2").show();
	}
	else {
		$("#PREdotdotdot").hide();
		$("#PREdotdotdot-2").hide();
	}
}
function TogglePostDots(status) {
	if (status) {
		$("#POSTdotdotdot").show();
		$("#POSTdotdotdot-2").show();
	}
	else {
		$("#POSTdotdotdot").hide();
		$("#POSTdotdotdot-2").hide();
	}
}

function ShowFiveLessPRE() {
	ChooseDesign.currentDisplayStartIndex = Math.max(ChooseDesign.currentDisplayStartIndex - ChooseDesign.numberPageNumbers, 1);
	ForceUpdateShownPages();
}
function ShowFiveMorePOST() {
	ChooseDesign.currentDisplayStartIndex = Math.min(ChooseDesign.currentDisplayStartIndex + ChooseDesign.numberPageNumbers, 
	        ChooseDesign.maxPages - ChooseDesign.numberPageNumbers);
	ForceUpdateShownPages();
}


function Paging_FlipToPage(pageNumber) {
	var currentlySelectedItem = $(".selectedNavItem");
	var newlySelectedItem = $("#pageNavItem" + pageNumber);
	var newlySelectedItem2 = $("#pageNavItem" + pageNumber + "-2");
	currentlySelectedItem.attr('class', 'pageNavItem');
	newlySelectedItem.attr('class', 'selectedNavItem');
	newlySelectedItem2.attr('class', 'selectedNavItem');
	ChooseDesign.currentPage = pageNumber;
	UpdateShownPages();
}


function IsCurrentlyViewingAll() {
    return ChooseDesign.currentPage == 'viewall';
}
