var t = null;
var cartopen = false;
var shoppingToteOpen = false;
var navigatingShoppingTote = false;

$(document).ready(function () {

    //$('body').append('<div class="background"/>');
    if (typeof ($.fn.bgStretcher) != 'undefined') {
        $('body').bgStretcher({
            images: ['/layout/img/common/background.jpg'],
            imageWidth: 2000,
            imageHeight: 2000,
            anchoring: 'left center',
            anchoringImg: 'left center'
        });
    }
    showMiniCart();
    //Search input dissapearing & re-appearing script
    $(".headerRight .searchBox .searchInput").focus(function () {
        if ($(this).attr("value") == "SEARCH")
        { $(this).attr("value", ""); }
    }); $(".headerRight .searchBox .searchInput").click(function () {
        if ($(this).attr("value") == "SEARCH")
        { $(this).attr("value", ""); }
    }); $(".headerRight .searchBox .searchInput").blur(function () {
        if ($(this).attr("value") == "")
        { $(this).attr("value", "SEARCH"); }
    });

    //Search input dissapearing & re-appearing script
    $(".searchInput").focus(function () {
        if ($(this).attr("value") == "Sign up for our mailing list")
        { $(this).attr("value", ""); }
    }); $(".searchInput").click(function () {
        if ($(this).attr("value") == "Sign up for our mailing list")
        { $(this).attr("value", ""); }
    }); $(".searchInput").blur(function () {
        if ($(this).attr("value") == "")
        { $(this).attr("value", "Sign up for our mailing list"); }
    });

    $('.findSize').click(function () {
        load_productEmailSignUp(document.getElementById("ContentPlaceHolder1_ProductIDHidden").value);
    });

    $('.primaryNav > li:last-child, .secondaryNav > li:last-child').addClass('lastElement');
    $('.primaryNav > li#shopFashion').hover(
		function () {
		    $(this).find('.secondaryNav').stop(true, true).fadeIn(500);
		},
		function () {
		    $(this).find('.secondaryNav').stop(true, true).fadeOut(500);
		}
	);
    $('.primaryNav > li#shopAccessories').hover(
		function () {
		    $(this).find('.secondaryNav').stop(true, true).fadeIn(500);
		},
		function () {
		    $(this).find('.secondaryNav').stop(true, true).fadeOut(500);
		}
	);
    $('.primaryNav > li#shopHome').hover(
		function () {
		    $(this).find('.secondaryNav').stop(true, true).fadeIn(500);
		},
		function () {
		    $(this).find('.secondaryNav').stop(true, true).fadeOut(500);
		}
	);
    $('.primaryNav > li#worldof').hover(
		function () {
		    $(this).find('.secondaryNav').stop(true, true).fadeIn(500);
		},
		function () {
		    $(this).find('.secondaryNav').stop(true, true).fadeOut(500);
		}
	);
    $('.bagWrap').hover(
		function () {
		    $('.myBag').stop(true, true).fadeIn(200);
		    $('.mainContent, .productInfo').css({ position: 'static' });
		},
		function () {
		    $('.myBag').stop(true, true).fadeOut(200);
		    $('.mainContent, .productInfo').css({ position: 'relative' });
		}
	);

    if ($('#residential').length) {
        initResidential();
    }


});            //document ready function




function MM_findObj(n, d) { //v4.01
    var p, i, x; if (!d) d = document; if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
        d = parent.frames[n.substring(p + 1)].document; n = n.substring(0, p);
    }
    if (!(x = d[n]) && d.all) x = d.all[n]; for (i = 0; !x && i < d.forms.length; i++) x = d.forms[i][n];
    for (i = 0; !x && d.layers && i < d.layers.length; i++) x = MM_findObj(n, d.layers[i].document);
    if (!x && d.getElementById) x = d.getElementById(n); return x;
}

function getElementByID_Master(e) {
    var ret = null;

    ret = MM_findObj(e);
    if (ret)
        return ret;

    ret = MM_findObj("ContentPlaceHolder1_" + e);
    if (ret)
        return ret;

    ret = MM_findObj("ContentPlaceHolder1$" + e);
    if (ret)
        return ret;

    ret = MM_findObj("ctl00_ContentPlaceHolder1_" + e);
    if (ret)
        return ret;

    ret = MM_findObj("ctl00$ContentPlaceHolder1$" + e);
    if (ret)
        return ret;

    return ret;
}

function render_cart_header(items, total) {
    var topdomain = document.domain;
    if (getElementByID_Master(total) == null || getElementByID_Master(items) == null)
        return;

    var xmlhttp = false;
    /*@cc_on@*/
    /*@if (@_jscript_version >= 5)
    // JScript gives us Conditional compilation, we can cope with old IE versions.
    // and security blocked creation of the objects.
    try {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (E) {
            xmlhttp = false;
        }
    }
    @end@*/
    if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
        try {
            xmlhttp = new XMLHttpRequest();
        } catch (e) {
            xmlhttp = false;
        }
    }
    if (!xmlhttp && window.createRequest) {
        try {
            xmlhttp = window.createRequest();
        } catch (e) {
            xmlhttp = false;
        }
    }

    try {
        if (topdomain) {
            var prot = "http://";
            if (isSecure())
                prot = "https://";
            //alert(prot + topdomain);
            xmlhttp.open("GET", prot + topdomain + "/store/os/shoppingcartcost.aspx", false);
            xmlhttp.send(null);
            var str = xmlhttp.responseText;
            xmlhttp.close;
            xmlhttp = false;
            var ary = str.split("|");

            if (ary.length > 1) {
                getElementByID_Master(total).innerHTML = ary[0];
                getElementByID_Master(items).innerHTML = ary[1];
            }
        }
    }
    catch (e) { }

    try {
        getElementByID_Master("CartLiteralSgl").style.display = "none";
        getElementByID_Master("CartLiteralPlural").style.display = "none";
        (getElementByID_Master("CartItemsLBGet").innerHTML == "1") ? getElementByID_Master("CartLiteralSgl").style.display = "inline" : getElementByID_Master("CartLiteralPlural").style.display = "inline";
    }
    catch (e) { }
}

function isSecure() {
    return location.protocol == 'https:';
}

function MM_goToURL() { //v3.0
    var i, args = MM_goToURL.arguments; document.MM_returnValue = false;
    for (i = 0; i < (args.length - 1); i += 2) eval(args[i] + ".location='" + args[i + 1] + "'");
}

function load_productEmailSignUp(id) {
    var url = '/store/productemailsignup.aspx?productid=' + id;
  
    $.ajax({
        url: url,
        success: function (html) { 
            $('#findSize').html(html);
            $('.sizeCF').msDropDown();
            $('.colorCF').msDropDown();
            $('.ddTitle').parent().addClass('detailDD');
            $('#quantity_arrow, .arrow').remove();
        },
        error: function (e) {
            alert(e.responseText);
        }
    });
}

function addToCantFindYourSize() {
    var color = document.getElementById('ProdColors') != null ? document.getElementById('ProdColors').value : document.getElementById('ContentPlaceHolder1_ProductColors') != null ? document.getElementById('ContentPlaceHolder1_ProductColors').value : null;
    var size = document.getElementById('ProdSizes').value;
    var email = document.getElementById('EmailAddress').value;
    var productid = document.getElementById('cfproductid').value;
    var name = document.getElementById('Name').value;
    var mailinglistchk = document.getElementById('NewsLetterChk');

    $('#cfmessage').css("color", "#D5A00F");
    $('#cfmessage').css("padding", "2px");
    $('#cfmessage').css('display', 'block');

    if (size == '-1') {
        $('#cfmessage').show();
        $('#cfmessage').html('Please select a size!');
        return false;
    }

    if (name == '') {
        $('#cfmessage').show();
        $('#cfmessage').html('Please enter a name!');
        return false;
    }

    if (email == '') {
        $('#cfmessage').show();
        $('#cfmessage').html('Please enter an email!');
        return false;
    }

    if (email != "") {
        if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) {
            //move past
        } else {
            return false;
        }
    }

    var params = '?productid=' + productid + '&colorid=' + color + '&sizeid=' + size + "&name=" + name + "&email=" + email + "&mailinglistchk=" + mailinglistchk.checked;

    var url = '/store/productemailsignupsubmit.aspx';
    url += params;

    $('#cfmessage').show();
    $('#cfmessage').html('processing...');

    $.ajax({
        url: url,
        success: function () {
            var notice = $('#cfmessage');
            notice.html('Information has been submitted!');
            $('#cfmessage').show();
        },
        error: function () {
            notice.html('Information has not been submitted!');
        }
    });

    return false;
}

function load_quicklook(id) {
    var url = '/store/QuickLook.aspx?productid=' + id + "&pageID=" + id + '&action=1';
    var pid = id;
    $.ajax({
        url: url,
        success: function (html) {
            $('#inline-1').html(html);
            BuildQuicklookJs();
            change_unitcost(id);
            initializeAllProducts('true');

            $('.quantityQL').msDropDown();
            $('.ddTitle').parent().addClass('detailDD');
            $('#quantity_arrow, .arrow').remove();

            $(".sizeChart").click(function () { $("#sizeChartTbl").show(); });
            $(".sizeChartclose").click(function () { $("#sizeChartTbl").hide(); });

            $(".verSlider").carouFredSel({
                items: 3,
                circular: false,
                infinite: false,
                auto: false,
                direction: 'up',
                prev: {
                    button: "#foo2_prev",
                    key: "left"
                },
                next: {
                    button: "#foo2_next",
                    key: "right"
                }
            });

            $(".findSize").fancybox({
                'padding': 0,
                'transitionIn': 'fade',
                'transitionOut': 'fade',
                'speedIn': 600,
                'speedOut': 200,
                'overlayOpacity': 0.7,
                'overlayColor': "#000"
            });
        },
        error: function (e) {
            alert(e.responseText);
        }
    });
}

function RefreshCart() {
    $.ajax({
        url: '/store/MiniCart.aspx',
        cache: false,
        success: function (html) {
            $('.bagWrap').html(html);
        }
    });
}

function RemoveItem(recid, qty) {
    navigatingTote = true;
    var url = '/store/removeminicartitem.aspx?recid=' + recid;
    $.ajax({
        url: url,
        cache: false,
        success: function (data) {
            $('.bagWrap').animate({ opacity: 0.50 }, 500);
            render_cart_header("CartItemsLBGet", "CartTotalLBGet");
            RefreshCart();
            $(".bagWrap").animate({ opacity: 1 }, 500);
        },
        error: function (err) {
            return false;
        }
    });
}

function showMiniCart() {
    $.ajax({
        url: '/store/minicart.aspx',
        cache: false,
        success: function (html) {
            $('.bagWrap').html(html);
        },
        error: function (err) {
            //alert(err.responseText);
        }
    });
}

function trigger_cartajax() {
    RefreshCart();
    $('.bagWrap').trigger('mouseenter');
   }

   // World of Kelly Global Functions
   var w = 806;
   var currentPosition = 0;

   generateAlbum = function (j, c, img) {
   	var x = "";
   	x += "<ul>\n";
   	for (i = 0; i <= j.length; i++) {
   		if (typeof j[i] !== 'undefined') {
   			x += "<li id=" + i + " class='sl'><img src='" + j[i].image + "' class='slideimg'  /></li>\n";
   		}
   	}
   	x += "</ul>\n";

   	$(c).html(x);
   	setEvents(c, j.length);
   }
   setEvents = function (c, l) {
   	$('#prev').hide();
   	$('a.next, a.prev').live('click', function (e) {
   			currentPosition = (e.target.id == 'next') ? currentPosition + 1 : currentPosition - 1;
   			$('' + c + ' ul').animate({
   				'left': w * (-currentPosition)
   			}, 250, 'swing');
   			manageControls(currentPosition, l);
   	});

   }
   manageControls = function (position, numberOfSlides) {
   	if (position == 0) { $('#prev').hide() } else { $('#prev').show() }
   	if (position == numberOfSlides - 1) { $('#next').hide() } else { $('#next').show() }
   }
   setBreadCrumb = function () {

   }

   getHashTagVal = function (key) {
   	var ret = new RegExp("[\#&]" + key + "=([^&#]*)").exec(window.location.href);
   	return (ret != null) ? ret[1] : "";
   }
   getQuerystring= function(key, default_) {
   	if (default_ == null) default_ = "";
   	key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
   	var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
   	var qs = regex.exec(window.location.href);
   	if (qs == null)
   		return default_;
   	else
   		return qs[1];
   }

