﻿Type.registerNamespace('PhotoSite');

var giftService = null;
var productView = null;

function initServiceView() {
    if (!giftService) {
        giftService = new IGiftService();
    }

    if (!productView) {
        productView = new PhotoSite.photoGiftGroup();
    }

    if (!categoryService)
        categoryService = new ICategoryService();
}

var photoGiftGroups = new Array();

PhotoSite.photoGift = function(encId, encCategoryId, encProductPlacementId, name, thumbUrl, price, type, description, options, layoutKey, reWrittenUrl) {
    this._encId = encId;
    this._encCategoryId = encCategoryId;
    this._encProductPlacementId = encProductPlacementId;
    this._name = name;
    this._description = description;
    this._thumbUrl = fileExists(thumbUrl.replace('../', '/')) ? thumbUrl.replace('../', '/') : "/images/no_image" + SR.LanguageSuffix + ".gif";
    this._price = price;
    this._type = type;
    this._options = options;
    this._layoutKey = layoutKey;
    this._reWrittenUrl = reWrittenUrl;
}

PhotoSite.photoGiftSubGroup = function(encId, encCategoryId, encProductPlacementId, name, description, thumbUrl, price, layoutKey) {
    this._encId = encId;
    this._encCategoryId = encCategoryId;
    this._encProductPlacementId = encProductPlacementId;
    this._name = name;
    this._description = description;
    this._thumbUrl = fileExists(thumbUrl.replace('../', '/')) ? thumbUrl.replace('../', '/') : "/images/no_image" + SR.LanguageSuffix + ".gif";
    this._price = price;
    this._type = "Category";
    this._layoutKey = layoutKey;
}
PhotoSite.photoGiftSubGroup.prototype = {
    render: function(parent) {

        var container = this._domElement = document.createElement('div');

        container.id = this._encId + '_product_thumb';
        container.className = 'gift_content';

        var sb = new Sys.StringBuilder();

        if (new RegExp('collage').test(this._name.toLowerCase()))
            this._type = "Collages";
        else if (new RegExp('newspapers').test(this._name.toLowerCase()))
            this._type = "Newspapers";
        if (this.productType == "EnhancementPrints")
            this._type = "EnhancementPrints";

        var name = this._name == null || this._name.toString().trim() == '' ? "&nbsp;" : sanitizeText(this._name);

        sb.append("<div class='product_listing_thumb' style='width:120px'><p>");
        sb.append("<a href=\"javascript:selectPhotoGift('");
        sb.append(this._type);
        sb.append("','");
        sb.append(this._encId);
        sb.append("','");
        sb.append(this._encCategoryId);
        sb.append("','");
        sb.append(this._encProductPlacementId);
        sb.append("','");
        sb.append(this._layoutKey);
        
        sb.append("')\"><img src='");
        sb.append(fileExists(this._thumbUrl) ? this._thumbUrl : "../images/no_image" + SR.LanguageSuffix + ".gif");
        sb.append("' border='0' alt='");
        sb.append(name);
        sb.append("' title='Click here for ");
        sb.append(name);
        sb.append("'/></a></p></div>");
        sb.append("<div class='product_listing_desc'><h3 class='product_label'>");
        sb.append(name);
        sb.append("</h3><h1 class='price_red'><p>" + canUseFrom(this._price) + "&nbsp;");
        sb.append(this._price);
        sb.append("</p></h1><p>");

        var description = this._description == null || this._description.toString().trim() == '' ? "&nbsp;" : sanitizeText(this._description);

        sb.append(description);
        sb.append("</div></div><div class='product_listing_btn' style='padding-top: 90px'><a href=\"javascript:selectPhotoGift('");
        sb.append(this._type);
        sb.append("','");
        sb.append(this._encId);
        sb.append("','");
        sb.append(this._encCategoryId);
        sb.append("','");
        sb.append(this._encProductPlacementId);
        sb.append("','");
        sb.append(this._layoutKey);
        sb.append("')\"><img src='/images/btns/btn_start_here" + SR.LanguageSuffix + ".gif' border='0' /></a></div>");

        container.innerHTML = sb.toString();
        parent.appendChild(container);
    }
}


function canUseFrom(price) {
    var leastPrice = 0;
    try {
        leastPrice = parseFloat(price.replace("$", "").replace("£", ""));
    }
    catch (e) { }

    return leastPrice > 0 ? SR.From : "";
}

PhotoSite.photoGift.prototype =
{
    _type: null,
    _domElement: null,

    render: function(parent) {

        var container = this._domElement = document.createElement('div');

        container.id = this._encId + '_product_thumb';
        container.className = 'gift_content';

        var htmlMarkup = new Sys.StringBuilder();

        var name = this._name == null || this._name.toString().trim() == '' ? "&nbsp;" : sanitizeText(this._name);

        htmlMarkup.append("<div class='product_listing_thumb' style='width:120px'><p>");
        htmlMarkup.append("<a href=\"javascript:selectPhotoGift('");
        htmlMarkup.append(this._type);
        htmlMarkup.append("','");
        htmlMarkup.append(this._encId);
        htmlMarkup.append("','");
        htmlMarkup.append(this._encCategoryId);
        htmlMarkup.append("','");
        htmlMarkup.append(this._encProductPlacementId);
        htmlMarkup.append("','");
        htmlMarkup.append(this._layoutKey);
        htmlMarkup.append("','");
        htmlMarkup.append(this._reWrittenUrl);         
        htmlMarkup.append("')\"><img src='");
        htmlMarkup.append(this._thumbUrl);
        htmlMarkup.append("' border='0' alt='");
        htmlMarkup.append(name);
        htmlMarkup.append("' title='Click here for ");
        htmlMarkup.append(name);
        htmlMarkup.append("'/></a></p></div>");
        htmlMarkup.append("<div class='product_listing_desc'><h3 class='product_label'>");
        htmlMarkup.append(name);
        htmlMarkup.append("</h3><h1 class='price_red'><p>");
        htmlMarkup.append(canUseFrom(this._price) + "&nbsp;" + this._price);
        htmlMarkup.append("</p></h1><p>");

        //htmlMarkup.append("<div class='gift_features_container'>");

        //        if (this._options.length > 0) {
        //            htmlMarkup.append("<div class='gift_features_separator'>");
        //            htmlMarkup.append(this.getOptionsMarkup(this._options));
        //            htmlMarkup.append("</div>");
        //        }
        //        else {
        //            //Add empty space
        //            htmlMarkup.append("<div class='empty_gift_features_container'>&nbsp;</div>");
        //        }


        var description = this._description == null || this._description.toString().trim() == '' ? "&nbsp;" : sanitizeText(this._description);

        //htmlMarkup.append("<div class='gift_features_separator'>");
        htmlMarkup.append(description);
        //htmlMarkup.append("</div>");

        //htmlMarkup.append("<div class='start_here'>")
        htmlMarkup.append("</div><div class='product_listing_btn' style='padding-top: 90px'><a href=\"javascript:selectPhotoGift('");
        htmlMarkup.append(this._type);
        htmlMarkup.append("','");
        htmlMarkup.append(this._encId);
        htmlMarkup.append("','");
        htmlMarkup.append(this._encCategoryId);
        htmlMarkup.append("','");
        htmlMarkup.append(this._encProductPlacementId);
        htmlMarkup.append("','");
        htmlMarkup.append(this._layoutKey);
        htmlMarkup.append("','");
        htmlMarkup.append(this._reWrittenUrl);        

        htmlMarkup.append("')\"><img src='/images/btns/btn_start_here" + SR.LanguageSuffix + ".gif' border='0'/></a></div>");

        container.innerHTML = htmlMarkup.toString();
        parent.appendChild(container);
    },

    getOptionsMarkup: function(options) {

        var optionMarkup = new Sys.StringBuilder();

        for (var i = 0; i < options.length; i++) {

            var option = options[i];

            if (option.OptionValues.length > 0) {

                optionMarkup.append("<div class='preview_features' style='width: 120px;'><p><strong>");
                optionMarkup.append(option.Name);
                optionMarkup.append(":</strong></p>");
                optionMarkup.append("<ul>");

                for (var j = 0; j < option.OptionValues.length; j++) {

                    var optionValue = option.OptionValues[j];

                    optionMarkup.append("<li>");
                    optionMarkup.append(optionValue.Text);

                }

                optionMarkup.append("</ul>");
                optionMarkup.append("</div>");
            }

        }

        return optionMarkup.toString();

    }

}

PhotoSite.photoGiftGroup = function(groupId) {
    this._groupId = groupId;
}

PhotoSite.photoGiftGroup.prototype =
{
    _photoGifts: new Array(),

    addPhotoGift: function(photoGift) {
        this.photoGifts.push(photoGift);


    },

    getPhotoGifts: function() {
        return this._photoGifts;
    }

}

function selectPhotoGift(type, rpId, id, pplId, layoutKey, reWrittenUrl) {

    if (isEmptyOrEncryptedZero(layoutKey)) {
        switch (type.toLowerCase()) {
            case 'category':
                checkSessionTimeout();
                if (rpId != '' & rpId != null & photoGiftGroups.length > 0 & !isEmptyOrEncryptedZero(id)) {
                    if (renderSubcategoryContents(id, rpId))
                        break;
                }
                else if (!isEmptyOrEncryptedZero(rpId) & rpId != null & isEmptyOrEncryptedZero(id)) {
                    selectPhotoGift('', rpId, id, pplId, layoutKey)
                    break;
                }
                UpdateNavigation2(pplId, id);
                selectdeselect(selSubMenuDivPrefix + id, selSubMenuPrefix + id, pplId);
                break;
            case 'calendars':
                location.href = RootUrl + "album/calendar_options.aspx?q=" + rpId;
                break;
            case 'photocalendars':
            case 'photocalendar':
                location.href = RootUrl + "album/calendar_custom_options.aspx?q=" + rpId;
                break;
            case 'photobooks':
            case 'photobook':
                location.href = RootUrl + "album/photobook_landing.aspx";
                break;
            case 'collages':
                location.href = RootUrl + "album/collagepage.aspx";
                break;
            case 'cd':
            case 'photocd':
                location.href = photo_albumUrl + "?path=1ePyT1lSuBl5zKzO_BSU5WXU7pvw3lfgy";
                break;
            case 'newspapers':
                location.href = RootUrl + "album/personalised_newspaper_landing.aspx";
                break;
            default:
                if (isEmptyOrEncryptedZero(reWrittenUrl) || urlRewriteEnabled == "False")
                    location.href = RootUrl + "album/gifts_select_media.aspx?q=" + rpId;
                else if (!isEmptyOrEncryptedZero(pplId) && !isEmptyOrEncryptedZero(id) && isEmptyOrEncryptedZero(reWrittenUrl))
                    UpdateNavigation2(pplId, id);
                else
                    location.href = RootUrl + reWrittenUrl;
                break;
        }
    }
    else {
        try { updateNavigatorforSpecialisedGifts(rpId, id, pplId); } catch (e) { }

        if (isEmptyOrEncryptedZero(reWrittenUrl))
            location.href = RootUrl + "album/specialised_gifts_landing.aspx?q=" + id + "&lkey=" + layoutKey;
        else
            location.href = RootUrl + reWrittenUrl;
    }
}


function renderSubcategoryContents(catId, subCatId) {
    var photogiftGroup = getPhotoGiftGroup(catId);

    if (photogiftGroup != null) {
        var subGroup = null;
        subGroup = getPhotogiftSubcategoryBySubcategoryId(photogiftGroup.PhotoGiftSubGroupModels, subCatId);
        if (subGroup) {
            RenderProductCategoryContentResults(subGroup);
            return true
        }
    }
    return false;
}


function RenderProductCategoryContentResults(result) {

    var photoGiftGroup = result;

    var resultContainer = $get('gifts_landing_main_content');

    if (photoGiftGroup != null) {

        resultContainer.innerHTML = "";
        $get('gifts_categories_header').innerHTML = photoGiftGroup.Name;

        var categoryContents = new Array();

        //sort array contents
        var sortedPhotoGiftSubGroupModels = photoGiftGroup.PhotoGiftSubGroupModels.sort(sortModels);
        var sortedPhotoGiftModels = photoGiftGroup.GiftModels.sort(sortModels);

        //merge sorted contents
        categoryContents = categoryContents.concat(sortedPhotoGiftSubGroupModels, sortedPhotoGiftModels);

        if (categoryContents.length > 0) {
            for (var i = 0; i < categoryContents.length; i++) {

                var model = categoryContents[i];

                if (model != null) {
                    if (model.ModelType == "gift") {
                        var photoGift = new PhotoSite.photoGift(model.EncId, photoGiftGroup.Id, photoGiftGroup.ProductPlacementId, model.Name, model.ThumbUrl, model.FormatedLeastPrice, model.ProductType, model.Description, model.PhotoGiftOptions, model.LayoutKey, model.RetailerProductUrl);
                        photoGift.render(resultContainer);
                    }
                    else if (model.ModelType == "giftsubgroup") {
                        var photoGiftSubGroup = new PhotoSite.photoGiftSubGroup(model.Id, photoGiftGroup.Id, photoGiftGroup.ProductPlacementId, model.Name, model.Description, model.ThumbUrl, model.FormatedLeastPrice, model.LayoutKey);

                        photoGiftSubGroup.render(resultContainer);
                    }
                }
            }
        }
        if (!isGroupAlreadyRendered(photoGiftGroup.Id))
            photoGiftGroups.push(photoGiftGroup);
    }

    hideLoadingPopup();
}

function getPhotogiftSubcategoryBySubcategoryId(photoGiftGroupSubCategories, subCategoryIdtoReturn) {
    for (var i = 0; i < photoGiftGroupSubCategories.length; i++) {
        var subGroup = photoGiftGroupSubCategories[i];
        if (subGroup.Id == subCategoryIdtoReturn)
            return subGroup;
    }
}

function isGroupAlreadyRendered(groupId) {

    for (var i = 0; i < photoGiftGroups.length; i++) {
        var group = photoGiftGroups[i];
        if (group.Id == groupId)
            return true;
    }
    return false;
}

function getPhotoGiftGroup(groupId) {
    for (var i = 0; i < photoGiftGroups.length; i++) {
        var group = photoGiftGroups[i];
        if (group.Id == groupId)
            return group;
    }
    return null;
}

function GetProductCategoryContent() {
    showLoadingPopup(res_loadingText);
    initServiceView();
    giftService.GetCategoryPhotoGiftModelsInstance(OnGotProductCategoryContentResult, gotError);
}

function OnGotProductCategoryContentResult(result) {
    if (result) {
        RenderProductCategoryContentResults(Sys.Serialization.JavaScriptSerializer.deserialize(result));
    }
}

var selSubMenuPrefix = 'a_side_nav_category';
var selSubMenuDivPrefix = 'div_side_nav_sub_category';

function selectChosenSubMenuFromMaimMenu(ppId, catId) {

    if (isEmptyOrEncryptedZero(catId)) {
        renderAllCategoriesinProdPlacement(); return;
    }

    var selSubMenu = $get(selSubMenuPrefix + catId);
    var selSubMenuDiv = $get(selSubMenuDivPrefix + catId);

    if (selSubMenu != null && selSubMenuDiv != null) {
        selectdeselect(selSubMenuDiv.id, selSubMenu.id, ppId);
        renderCategorySample(selectedCategory, 'gifts_landing_main_content');
    }
    else
        renderAllCategoriesinProdPlacement();
}

var res_loadingText = SR.Loading;
var selectedCategory = '';

function selectdeselect(selectedCatDivId, selectedCatHeaderId, pplId) {

    var currentCategory = selectedCatHeaderId.substring(19);

    if (selectedCategory == currentCategory)
        return;

    if (selectedCategory != '') {
        var selSubMenuLinkPrefix = $get(selSubMenuPrefix + selectedCategory);
        if (selSubMenuLinkPrefix)
            selSubMenuLinkPrefix.className = "side_nav_cat_unselected";

        var selSubCatMenuDivPrefix = $get(selSubMenuDivPrefix + selectedCategory);
        if (selSubCatMenuDivPrefix)
            selSubCatMenuDivPrefix.className = "side_nav_sub_unselected";
    }
    var selCurrentSubMenuPrefix = $get(selSubMenuPrefix + currentCategory);
    if (selCurrentSubMenuPrefix)
        selCurrentSubMenuPrefix.className = "side_nav_cat_selected"

    var selCurrentSubMenuDivPrefix = $get(selSubMenuDivPrefix + currentCategory);
    if (selCurrentSubMenuDivPrefix)
        selCurrentSubMenuDivPrefix.className = "side_nav_sub_selected";

    selectedCategory = currentCategory;
    currentGroupId = '';
}

function renderAllCategoriesinProdPlacement() {

    var parent = $get('gifts_landing_main_content');

    showLoadingPopup(res_loadingText);

    for (var i = 0; i < categories.length; i++) {
        var cat = categories[i];

        var div = document.createElement("div");
        div.className = "product_listing";
        div.innerHTML = getCategorySampleHTML(cat);

        parent.appendChild(div);
    }

    if (categories.length > 0) {
        var placementId = categories[0].pplId;
        var placementName = "Gift Ideas";
        switch (placementId) {
            case '1wL31xSALXQG2BG4DLfsDPEzisRkMPCqF':
                placementName = "Canvas &amp; Posters";
                break;
            case '1Uz5De5GHPRTdeCaLBCHJggZ1bY0Hh0sb':
                placementName = "Restoration &amp; Caricatures";
                break;
            case '1tJHqTB,glCJdT3MYpet5WpqwOARm9GXE':
                placementName = "Gift Ideas"
                break;
        }
        $get('gifts_categories_header').innerHTML = placementName;
    }

    hideLoadingPopup();
}

function getCategorySampleHTML(cat) {

    if (cat == null)
        return '';

    var sb = new Sys.StringBuilder();

    if (cat.hasCategory.toLowerCase() == "true")
        cat.type = "Category";

    if (new RegExp('collage').test(cat.name.toLowerCase()))
        cat.type = "Collages";

    if (new RegExp('newspapers').test(cat.name.toLowerCase()))
        cat.type = "Newspapers";

    if (cat.productType == "EnhancementPrints")
        cat.type = "EnhancementPrints";


    var name = cat.name == null || cat.name.toString().trim() == '' ? "&nbsp;" : sanitizeText(cat.name);

    sb.append("<div class='product_listing_thumb' style='width:120px'><p>");
    sb.append("<a href=\"javascript:selectPhotoGift('");
    sb.append(cat.type);
    sb.append("','");
    sb.append(cat.rpId);
    sb.append("','");
    sb.append(cat.id);
    sb.append("','");
    sb.append(cat.pplId);
    sb.append("','");
    sb.append(cat.layoutKey);
    sb.append("','");
    sb.append(cat.reWrittenUrl);
    sb.append("')\"><img src='");
    sb.append(fileExists(cat.sampleImageUrl) ? cat.sampleImageUrl : "../images/no_image" + SR.LanguageSuffix + ".gif");
    sb.append("' border='0' alt='");
    sb.append(name);
    sb.append("' title='Click here for ");
    sb.append(name);
    sb.append("'/></a></p></div>");
    sb.append("<div class='product_listing_desc'><h3 class='product_label'>");
    sb.append(name);
    sb.append("</h3><h1 class='price_red'><p>" + canUseFrom(cat.minPrice) + "&nbsp;");
    sb.append(cat.minPrice);
    sb.append("</p></h1><p>");
    sb.append(cat.description);
    sb.append("</p></div><div class='product_listing_btn' style='padding-top: 90px'><a href=\"javascript:selectPhotoGift('");
    sb.append(cat.type);
    sb.append("','");
    sb.append(cat.rpId);
    sb.append("','");
    sb.append(cat.id);
    sb.append("','");
    sb.append(cat.pplId);
    sb.append("','");
    sb.append(cat.layoutKey);
    sb.append("','");
    sb.append(cat.reWrittenUrl);

    sb.append("')\"><img src='/images/btns/btn_start_here" + SR.LanguageSuffix + ".gif' border='0' /></a></div></div>");

    return sb.toString();
}

function renderCategorySample(id, parentDivId) {

    var parentDiv = $get(parentDivId);
    var cat = getCategoryById(id);

    if (cat) {
        $get('divPromo').style.display = "none";
        $get('gifts_categories_header').innerHTML = cat.name;
        parentDiv.innerHTML = getCategorySampleHTML(cat);
    }
}

function updateSelectedCategoryNavigator(catId, pplId) {

    if (currentGroupId == catId)
        return;

    if (!isEmptyOrEncryptedZero(catId) & currentGroupId != catId)
        currentGroupId = catId;

    if (!categoryService)
        categoryService = new ICategoryService();

    var state = new Object();
    state.EProductPlacementID = pplId;
    state.ECategoryID = catId;

    categoryService.UpdateNavigator2(state, true, function() { renderCategorySample(catId, 'gifts_landing_main_content'); }, gotError);
}

function getCategoryById(id) {

    for (var i = 0; i < categories.length; i++) {

        var cat = categories[i];
        if (cat.id == id)
            return cat;
    }

    return null;
}

var currentGroupId = '';

function UpdateNavigation2(productPlacementContentId, productCategoryId, retailerProductId) {

    var groupId = productCategoryId;

    if (isEmptyOrEncryptedZero(groupId) & !isEmptyOrEncryptedZero(retailerProductId))
        groupId = retailerProductId;

    currentGroupId = groupId;

    if (categoryService == null)
        categoryService = new ICategoryService();

    if (!isGroupAlreadyRendered(groupId)) {
        var navigationState = new Object;

        navigationState.EProductPlacementID = productPlacementContentId;
        navigationState.ERetailerProductID = retailerProductId;
        navigationState.ECategoryID = productCategoryId;
        categoryService.UpdateNavigator2(navigationState, false, UpdateGiftNavigationSessionCompleted2, gotError);
    }
    else {
        //Get contents from local cache
        var contents = getPhotoGiftGroup(groupId);

        if (typeof contents != 'undefined' && contents != null)
            showLoadingPopup(res_loadingText);

        RenderProductCategoryContentResults(contents);
    }
}

function updateNavigatorforSpecialisedGifts(rpId, catid, pplId) {
    var state = new Object();

    state.EProductPlacementID = pplId;
    state.ECategoryID = catid;
    state.ERetailerProductID = rpId;

    if (categoryService == null)
        categoryService = new ICategoryService();

    categoryService.UpdateNavigator(state, false, function(res) {
        ////    alert(res); 
    }, gotError)
}

function isEmptyOrEncryptedZero(value) {
    return typeof value == "undefined" || value == "" || value == "1dEvH,sBwBIX9pvpibXIiNSHIpK2SU,Dj" || value == '1g,ZRY1n4Xt1UeK2KJo3UGNlOZyB05UEK';
}

function UpdateGiftNavigationSessionCompleted2(result) {
    var objResult = Sys.Serialization.JavaScriptSerializer.deserialize(result);
    var url = document.location.href;

    var productTypeId = parseInt(objResult.ProductTypeId);

    if (url.indexOf('https:') > -1) {
        document.location = '<%=AppGlobal.GetAbsoluteBaseUrl() %>/' + objResult.Url;
    }
    else if (objResult.ProductTypeId == '3' || objResult.ProductTypeId == '5' || objResult.ProductTypeId == '12') {
        GetProductCategoryContent();
    }
    else {
        document.location = RootUrl + objResult.Url;
    }
}

function sortModels(model1, model2) {
    if (model1 != null & model2 != null)
        return model1.Name >= model2.Name ? 1 : 0;
    else if (model1 != null & model2 == null)
        return 0;
    else if (model1 == null & model2 != null)
        return 1;
    else //default
        return 1;
}

function sanitizeText(texttoSanitize) {
    if (texttoSanitize == null)
        return "";
    var sanitizedText = texttoSanitize;
    sanitizedText = texttoSanitize.toString().replace("'", "&#39;").replace('"', '&quot;');

    return sanitizedText;
}

function initializeGiftSelectMediaOrderOptions() {

    var selectedPackageOption = $get("<%=SelectedPackageOption.ClientID %>");

    if (selectedPackageOption != null) {
        if (selectedPackageOption.value != "") {
            var defaultRpovId = selectedPackageOption.value;
            $get("opt_" + defaultRpovId).checked = 'checked';
            rpovTotal.innerHTML = $get("price_" + defaultRpovId).innerHTML;
        }
    }

    var basePrice = $get("basePrice");
    if (basePrice != null) {
        if (basePrice.innerHTML == "")
            rpovTotal.style.display = "";
    }
}



PhotoSite.photoGiftGroup.registerClass('PhotoSite.photoGiftGroup');
PhotoSite.photoGift.registerClass('PhotoSite.photoGift');
