// ------------------------------
// Groove Functionality
// ------------------------------



// kickoff
$(document).ready(function() {

    // Blog Sidebar List Bullets
    $(".sideBarItem li a").before("&raquo; ");

    // Input Field from AndyStratton.com
    $("input.populate, textarea.populate").each(function() {
        if ($(this).val() == "") {
            $(this).val($(this).attr("title"));
        }
    });
    $("input.populate, textarea.populate").focus(function() {
        if ($(this).val() == $(this).attr("title")) {
            $(this).val("");
        }
    });
    $("input.populate, textarea.populate").blur(function() {
        if ($(this).val() == "") {
            $(this).val($(this).attr("title"));
        }
    });

    // prevent right click
    //$("img").attr("oncontextmenu", "return false");

    // SIFU dropdown columns
    var numListItems = $("ul.sifuPopup > li").size();
    var colSize = Math.ceil(numListItems / 2);
    $("ul.sifuPopup li:lt(" + colSize + ")").addClass("col1");
    negMargin = (-($("ul.sifuPopup").height()) / 2);

    // sum up the heights, first col will always be biggest
    var col1Height = 0;
    var col2Height = 0;
    $("ul.sifuPopup li:lt(" + colSize + ")").each(function() { col1Height += ($(this).outerHeight() + 5); });
    $("ul.sifuPopup li:eq(" + colSize + ")").addClass("col2").css("marginTop", (col1Height) * -1);
    $("ul.sifuPopup li:gt(" + colSize + ")").addClass("col2");
    $("ul.sifuPopup li:gt(" + eval(colSize - 1) + ")").each(function() { col2Height += eval($(this).outerHeight() + 5); });

    // set the height based on the summed height
    $("ul.sifuPopup").css("height", (col2Height > col1Height ? col2Height : col1Height) + "px");

    // nav hover for sifu menu
    $("ul.nav li a.sifu, ul.sifuPopup").hover(function() {
        $("ul.nav li a.sifu").css("background-position", "right -44px").css("color", "#0e2037");
    }, function() {
        $("ul.nav li a.sifu").css("background-position", "left 0px").css("color", "#fff");
    });

    // drop down menu
    $("ul.nav").superfish();

    // slideshow
    $("#slideshow").tabs({ fx: { opacity: 'toggle'} }).tabs('rotate', 6000);

    // product image popup
    $('.fancy').fancybox({frameHeight: 390});

    // fancybox info popups
    $('.fancyPopup').fancybox({
        'hideOnContentClick': false,
        frameHeight: 470,
        frameWidth: 400
    });

    // fancybox info popups
    $('.fancyPopupWide').fancybox({
        'hideOnContentClick': false,
        frameHeight: 350,
        frameWidth: 600
    });



    // product multi image
    $(".thumbnails img").click(function() {
        var src = new Array(4);

        var isOriginal = $(this).attr("title") == "Original Image";

        src = ($(this).attr("src")).split(".", 2);

        if (!isOriginal)
            src[0] = src[0] + "_";

        src = src.join(".");
        src = src.split("/", 4);

        src[2] = "medium";
        var mediumSrc = src.join("/");
        src[2] = "large";
        var largeSrc = src.join("/");

        //alert(mediumSrc);

        $(".productImages .productImage a img").attr("src", mediumSrc);
        $(".productImages .productImage a, .productImages span a").attr("href", largeSrc);
    });

    // product review snippet
    var numReviews = $(".productSummary .review span.num").text();
    if (numReviews == 0) {
        $(".productSummary .review p").text("There have been no reviews for this product.");
    }
    else {
        var reviewSnippet = new Array(20);
        var elipsis = "";
        reviewSnippet = ($("li.comment:first p.commentContent").text()).split(" ", 20);
        if (reviewSnippet.length > 20)
            elipsis = "...";
        reviewSnippet = '"' + reviewSnippet.join(" ") + elipsis + '"';
        $(".productSummary .review p").text(reviewSnippet);
    }

    // product review show all button
    if (numReviews > 1) {
        $(".showAll").html('<a href="#">View All</a>');
        $("ul.reviewList li:gt(0)").hide();
    }
    $("span.showAll a").click(function() {
        $("#reviews ul li").slideDown('slow');
        $(this).hide();
        return false;
    });

    // search results page row colors
    $("ul.searchResults li:odd").css("background-color", "#f2f2f2");

    // category listing normalize height
    $("#categoryListing").eqHeight({ restrictTo: "li.item" });

    // Related Products
    $("#relatedProducts ul.content li:last").addClass("last");

    // correct the tab indices
    var currIndex = 1;
    $("input[type='text'], input[type='password'], input[type='radio'], input[type='checkbox'], select, textarea, #btnContinueCheckout").each(function() {
        $(this).attr("tabindex", currIndex);
        currIndex++;
    });
    //}).eq(0).focus();

    // credit card icon selection
    $("#CardType").change(function() {
        var selectedIconID = $(this).val();

        $("span.creditCardIcons img").each(function() {
            var currIconID = $(this).attr("id");
            var currIconTag = $(this).attr("title");

            if (currIconID.toUpperCase() != selectedIconID.toUpperCase())
                $(this).attr("src", "/skins/Skin_1/images/" + currIconTag + "_bw.gif");
            else
                $(this).attr("src", "/skins/Skin_1/images/" + currIconTag + ".gif");
        });
    });

    $("#account_information #password, #account_information #password2, #CustPassword2, #CustPassword").blur(function() {
        var pwLength = $(this).val().length;

        if (pwLength < 5 && pwLength > 0)
            alert("Please enter a password 5 characters or more characters in length.");
    });

    // loading screen
    var jLoad = $("<div></div>");
    var jLoadImage = $("<img>");

    jLoadImage.attr("src", "/skins/Skin_1/images/loading.gif");
    jLoadImage.css({ margin: "0 auto", display: "block", marginTop: ($(window).height() / 2) - 50 });

    jLoad.attr("id", "loadWait");
    jLoad.css({ position: "fixed", "z-index": 999, width: $(window).width(), height: "100%", top: "0px", left: "0px", opacity: "0.8", backgroundColor: "#000000" });
    jLoad.hide();
    jLoad.append(jLoadImage);

    $("body").append(jLoad);

    // bind the dom elements to init the load screen
    var aryBindings = [];
    aryBindings.push("body.checkout #btnChangeAddress");
    aryBindings.push("body.checkout #pnlCartAllowsShippingMethodSelection input[type='radio']");
    aryBindings.push("body.checkout #pnlPaymentOptions input[type='radio']");
    aryBindings.push("body.checkout #btnUpdateShipMethods");
    aryBindings.push("body.checkout #btnUpdateCart3");

    $(aryBindings.join(", ")).click(function() { $("#loadWait").show(); });
});
// end kickoff

// functions for onload (e.g., after images are loaded)
window.onload = function()
{
    // product image zoom
    	var options = {
	    zoomWidth: 200,
	    zoomHeight: 350,
            xOffset: 16,
            yOffset: 0,
            position: "right",
            title:false
	};
	$(".fancy_jqzoom").jqzoom(options);

}

$("div").bind("contextmenu",function(e){  
    return false;  
});

function ExpandMiniCart()
{
    var aryItems = [];
    var passedArgs = arguments;

    $(document).ready(function()
    {
        for (i = 0; i < passedArgs.length; i++)
            aryItems.push("#item_" + passedArgs[i]);

        $(aryItems.join(", ")).animate({ "backgroundColor": "#f2e255" }, 2000).animate({ "backgroundColor": "#ffffff" }, 2000);
    });
}



// <-- REQUIRED FOR FORGOT PASSWORD TOGGLE
function forgotpassword_toggle() {
    if ($("#forgot-display").is(":hidden")) {
        $("#forgot-display").slideDown("slow");
    }
    else {
        $("#forgot-display").slideUp("fast");
    }
}
// END FORGOT PASSWORD TOGGLE -->

// CONFIGURE THE COUNTRY/REGION/STATE TOGGLE
// Ryan Peters
var countryDivisionLabel = { "Algeria": "Province", "Angola": "Province", "Argentina": "Province", "Armenia": "Region", "Australia": "State", "Austria": "State", "Azerbaijan": "Province", "Azores": "Island", "Bahamas": "Region", "Bangladesh": "Division", "Belarus": "Province", "Belgium": "Region", "Belize": "District", "Benin": "Department", "Bhutan": "District", "Bolivia": "Department", "Bosnia": "Canton", "Botswana": "District", "Brazil": "Estado", "British Virgin Isles": "Island", "Brunei": "District", "Bulgaria": "Province", "Burkina Faso": "Region", "Burundi": "Province", "Cambodia": "Province", "Cameroon": "Province", "Canada": "Province", "Canary Islands": "Island", "Cape Verde": "County", "Cayman Islands": "District", "Central African Republic": "Prefecture", "Chad": "Region", "Chile": "Region", "China": "Province", "Colombia": "Department", "Cook Islands": "Island", "Costa Rica": "Province", "Cote DIvoire": "State/Province", "Croatia": "County", "Cyprus": "District", "Czech Republic": "Region", "Denmark": "Region", "Djibouti": "Region", "Dominican Republic": "Province", "Ecuador": "Province", "Egypt": "Governarates", "El Salvador": "Department", "England": "County", "Equitorial Guinea": "Province", "Eritrea": "Region", "Estonia": "County", "Ethiopia": "Region", "Faeroe Islands": "Region", "Fiji": "Island", "Finland": "Province", "France": "Region", "French Guiana": "Canton", "French Polynesia": "Island", "Gabon": "Province", "Gambia": "Division", "Georgia": "State", "Germany": "State", "Ghana": "Region", "Greece": "Periphery", "Grenada": "Parish", "Guatemala": "Department", "Guinea": "Region", "Guinea-Bissau": "Region", "Guyana": "Region", "Haiti": "Department", "Holland": "Province", "Honduras": "Department", "Hong Kong": "District", "Hungary": "County", "Iceland": "Region", "India": "State", "Indonesia": "Province", "Iraq": "Governorates", "Israel": "District", "Italy": "Region", "IvoryCoast": "Region", "Jamaica": "Parish", "Japan": "Prefecture", "Jordan": "Governarates", "Kazakhstan": "Province", "Kenya": "Province", "Kiribati": "Island", "Kuwait": "Governorates", "Kyrgyzstan": "Province", "Laos": "Province", "Latvia": "District", "Lebanon": "Governarates", "Lesotho": "District", "Liberia": "County", "Libya": "Governarates", "Lithuania": "County", "Luxembourg": "Province", "Macedonia": "Municipality", "Madagascar": "Province", "Madeira": "Municipality", "Malawi": "District", "Malaysia": "Region", "Mali": "Region", "Malta": "Island", "Marshall Islands": "District", "Martinique": "Canton", "Mauritania": "Region", "Mauritius": "District", "Mexico": "Estado", "Micronesia": "Island", "Moldova": "District", "Monaco": "Ward", "Mongolia": "Province", "Morocco": "Region", "Mozambique": "Province", "Myanmar": "State", "N. Mariana Islands": "Island", "Nauru": "District", "Nepal": "Zone", "Netherlands": "Province", "Netherlands Antilles": "Island", "New Caledonia": "Province", "New Zealand": "Region", "Nicaragua": "Department", "Niger": "Department", "Nigeria": "State", "Northern Ireland": "County", "Norway": "Region", "Oman": "Governarates", "Pakistan": "Province", "Palau": "State", "Panama": "Province", "Papua New Guinea": "Province", "Paraguay": "Department", "Peoples Rep of China": "Province", "Peru": "Region", "Philippines": "Province", "Pitcairn Island": "Island", "Poland": "Province", "Ponape": "Municipality", "Puerto Rico": "Municipality", "Qatar": "Municipality", "Republic of Congo": "Region", "Republic of Ireland": "County", "Republic of Yemen": "Governarates", "Romania": "County", "Russia": "Federal Subject", "Rwanda": "Province", "San Marino": "Municipality", "Scotland": "County", "Senegal": "Region", "Seychelles": "District", "Sierra Leone": "Province", "Singapore": "Region", "Slovakia": "Region", "Slovenia": "Region", "Solomon Islands": "Province", "South Africa": "Province", "South Korea": "Province", "Spain": "Province", "Sri Lanka": "Province", "St. Croix": "District", "St. Kitts & Nevis": "Parish", "St. Lucia": "Quarter", "St. Vincent and Grenadine": "State/Province", "Sudan": "State", "Suriname": "District", "Swaziland": "District", "Sweden": "County", "Switzerland": "Canton", "Syria": "Governarates", "Tajikistan": "Province", "Tanzania": "Region", "Thailand": "Province", "Togo": "Region", "Truk": "Municipality", "Tunisia": "Governorates", "Turkey": "Region", "Turkmenistan": "Province", "Turks & Caicos Islands": "Island", "Tuvalu": "Island", "Uganda": "District", "Ukraine": "Province", "United Arab Emirates": "Emirate", "United Kingdom": "County", "United States": "State", "Uruguay": "Department", "US Virgin Islands": "District", "Uzbekistan": "Province", "Vanuatu": "Province", "Venezuela": "Estado", "Vietnam": "Province", "Wales": "County", "Western Samoa": "District", "Yap": "Municipality", "Yugoslavia": "Province", "Zambia": "Province", "Zimbabwe": "Province" };
var isRequired;

function SetLocalizationFields(containerID, country, options)
{
    var isRequired = options && options.isRequired;
    var maintainStates = options && options.maintainStates;

    var jDomesticFields = $("#" + containerID + " tr.trZipCode");
    var jStateList = $("#" + containerID + " tr.trStateProvince select");
    var jStateText = $("#" + containerID + " tr.trStateProvince input[type='text']");
    var jStateLabel = $("#" + containerID + " tr.trStateProvince td.col1");

    var divisionType = countryDivisionLabel[country];

    if (divisionType == null)
        divisionType = "Region";

    if (isRequired)    
        jStateLabel.html("<b>*" + divisionType + ":</b>");
    else
        jStateLabel.html(divisionType);

    if (!maintainStates)
    {
        jStateText.removeAttr("value");
        jStateList.children("option:eq(0)").attr("selected", "selected");
    }

    if (country == "United States" || country == "Canada")
    {
        jStateList.show();
        jStateText.hide();
    }
    else
    {
        jStateList.hide();
        jStateText.show();
    }

    /*if (country == "United States")
        jDomesticFields.show();
    else
        jDomesticFields.hide();*/
}


// <-- REQUIRED FOR DEBUGMODE
function toggleSingleDiv(id) {
    if ($("#" + id).is(":hidden")) {
        $("#" + id).slideDown("fast");
    }
    else {
        $("#" + id).slideUp("fast");
    }
    return false;
}
// END DEBUGMODE -->




function PreLoadImages()
{
    for (image in arguments)
    {
        var loadImage = new Image();
        loadImage.src = image;
    }
}



//------------------------------------------------
// Store Front Default Functionality Below
//------------------------------------------------

//----------Switches Visibility on Items----------
function switchVisibility(obj) {
    var el = document.getElementById(obj);

    if ( el.style.display != "none" ) {
        el.style.display =
        'none';
    }

    else {
        el.style.display =
        '';
    }
}

function switchVisibilityCheckbox(obj, checkbox) {

    var el = document.getElementById(obj);

    if ( el.style.display != "none" && document.getElementById(checkbox).checked == true) {
        el.style.display =
        'none';
    }

    else if (document.getElementById(checkbox).checked == false) {
        el.style.display =
        '';
    }
}

function switchVisibilityCheckout(obj, checkbox) {
    var el = document.getElementById(obj);

    var style_attrib = window.document.createAttribute("style");
        style_attrib.nodeValue = "display: none;";
    //scDiv.attributes.setNamedItem(style_attrib);

    if (document.getElementById(checkbox).checked == true) {
        el.style.display =
        'none';
    }

    else if (document.getElementById(checkbox).checked == false) {
        el.style.display =
        '';
    }
}

//-------------Validate Function For Quantity Selection Kit Group-------------
function validatebox()
{
	var msg1='Please verify your quantities and select exactly';
    var kitgroup=document.forms['kit'].elements['kgid'];
    
    var kid=kitgroup.value;
    var kitgroupid=new Array();
    kitgroupid=kid.split(",");
   
	for(var j=0; j<kitgroupid.length-1; j++)
	{
	    var gid=document.forms['kit'].elements['groupid_' + kitgroupid[j]];
	    group_id=gid.value;
	    var mid=document.forms['kit'].elements['max_number_' + kitgroupid[j]];
	    max_number=mid.value;
	    var tid=document.forms['kit'].elements['textboxid_' + kitgroupid[j] ];
	    var textboxid1=tid.value
	    var mval=document.forms['kit'].elements['max_value_' + kitgroupid[j] ];
	    var max_value=parseInt(mval.value);
	    var ids =new Array();
	    ids=textboxid1.split(",");
	    var sum=0;
	    var i=0; 
	      
	    while(max_number > 0)
	    {
		    if(ids[i]!="")
		    {
			    var value='KitGroupID_' + group_id + '_TextOption_' + ids[i];
			    var sum1=document.forms['kit'].elements['KitGroupID_' + group_id + '_TextOption_' + ids[i]];
			    i=i+1;
	            if (sum1.value!="")
                {
          	        sum=sum + parseInt(sum1.value);
			    }
			    max_number=max_number-1;
		    }
	    }
	
	    if (parseInt(sum) < parseInt(max_value) )
	    {
		    window.alert(msg1 + ' ' + max_value + '.');
	    	return false;
	    }
	    else if (parseInt(sum) > parseInt(max_value) )
	    {
		    window.alert(msg1 + ' ' + max_value + '.');
	   		return false;
	    }
	    
	    
	    if(ids.length>=0)
	    {
	    	ids.pop();
	    }
	    
	    sum=0;
	    group_id=0;
		max_number=0;
		max_values=0;
	}
}
