/*
    Method to make an ajax call and populate a select box with a list of cities that have
    either a store or a famous project and are within a particular selected state.
    Copyright (C) 2000-2007 Kohler Company.    All Rights Reserved.
    Author: Chris O'Connell
    Date Created: 10/19/07
    @param stateSelect The ID of the select box that has the selected state
    @param citySelect the ID of the select box that needs to be populated with the list
    of cities
    @param type the type of cities, those with stores (i.e. STORES) or those
    with Famous Projects (i.e. PROJECTS).
 */
function getCitiesForState(stateSelect, citySelect, type){

    var selectedState = $(stateSelect).selectedValues();

    $(citySelect).removeOption(/./);

    if (selectedState == null || selectedState[0] == 'XXX' || selectedState == ''){
        // this means the user hasn't selected anything, so we just clear out
        // the cities and add a default


        //$(citySelect).addOption('XXX', '?');

    } else {

        $(citySelect).ajaxAddOption('/ajax/getStoreCities.cn',
                {stateName: selectedState, cityType: type}, 
                false);

    } 

}

function testCookie() {
    var tmpcookie = new Date();
    var chkcookie = (tmpcookie.getTime() + '');
    document.cookie = "chkcookie=" + chkcookie + "; path=/";
    return document.cookie.indexOf(chkcookie, 0) >= 0;
}

function addOpenCompare() {
    var itemArray = [];
    var hasChecked = false;
    if ($('input.addToCompare')) {
        $('input.addToCompare').each(function () {
            if ($(this)[0].checked) {
                hasChecked = true;
                if (!compareArrayContainsValue($(this).val())) {
                   itemArray.push($(this).val());
                }
            }
        });
    }

    if (!hasChecked) {
        return openComparePopUpWindow('/onlinecatalog/compare/index.cn', compareWindow);
    } else {
        updateCompareCookie(itemArray);
        openCompare(itemArray);
        return compareWindow;
    }
}

function openComparePopUpWindow(theURL, theWindow) {
    if (!testCookie()) {
        alert(compareNoCookiesAlertText);  // defined in the decorator
        return null;
    }
    var refresh = (arguments.length == 3) ? arguments[2] : false;
    if(theWindow == null || typeof(theWindow)=='undefined') {
		theWindow = window.open(theURL,'CompareWindow','width=825,height=800,scrollbars=1,location=no,menubar=no,toolbar=no,status=no,resizable=no');
    } else if (refresh || theWindow.closed) {
		delete theWindow;
        theWindow = window.open(theURL,'CompareWindow','width=825,height=800,scrollbars=1,location=no,menubar=no,toolbar=no,status=no,resizable=no');
	}
    theWindow.focus();
    return theWindow;
}

function openVideo(videoName, vidWindow) {
    if(vidWindow == null || typeof(vidWindow)=='undefined') {
		vidWindow = window.open("/pov/video/index.cn?video=" +videoName,'ChinaVideos','width=362,height=360,scrollbars=no,location=no,menubar=no,toolbar=no,status=no,resizable=no');
    } else if (vidWindow.closed || "video="+videoName != vidWindow.location.search) {
		delete vidWindow;
        vidWindow = window.open("/pov/video/index.cn?video=" +videoName,'ChinaVideos','width=362,height=360,scrollbars=no,location=no,menubar=no,toolbar=no,status=no,resizable=no');
	}
    vidWindow.focus();
    return vidWindow;
}
/**
 * Returns true if 's' is contained in the array 'a'
 */
function arrayContains(a, e) {
	for(var j=0;j<a.length;j++) { if(a[j]==e) { return true; }}
	return false;
}
/**
 * Removes duplicates in the array 'a'
 */
function arrayUnique(a) {
	var tmp = [];
	for(var i=0;i<a.length;i++){
		if(!arrayContains(tmp, a[i])){
			tmp[tmp.length]=a[i];
		}
	}
	return tmp;
}


//
// Function to clear default copy from search box
//
function clearDefault(field) {
	if (field.value == '关键字/产品代码') {
		field.value = '';
	}
}

function convertToNumber(numIn) {
	var result = 0;
	if (numIn.toString().indexOf('p') > -1) {
		result = parseInt(numIn.substring(0,numIn.indexOf('px')));
	} else {
		result = parseInt(numIn)
	}
	if (isNaN(result)) {
		return 0;
	}
	return result;
}

function callLightbox(obj) {
	$(obj).each(function(i){
		var thisImage = $(this).children();
		var mtop = convertToNumber(thisImage.css('marginTop'));
		var mright = convertToNumber(thisImage.css('marginRight')) + 3;
		
		var imgHeight =  convertToNumber(thisImage[0].height) - 19;
		if (mtop > 0) {
			imgHeight =  imgHeight - mtop;
		};
		thisImage.after('<div style="position:absolute; top:' + imgHeight + 'px; right:' + mright + 'px; cursor:pointer; cursor:hand;"><img src="/common/images/icon-lightbox.gif" width="16" height="16" alt="" border="0"></div>');
	});
	$(obj).lightBox();
}

function callLightboxDtl(obj) {
	$(obj).each(function(i){
		var thisImage = $(this).children();
		thisImage.after('<div style="position:absolute; bottom:9px; right:9px; cursor:pointer; cursor:hand;"><img src="/common/images/icon-lightbox.gif" width="16" height="16" alt="" border="0"></div>');
	});
	$(obj).lightBox();
}

function callNotSelected(obj) {
	$(obj).each(function(i){
		$(this).html($(this).html() + '<div style="position:absolute; top:16px; right:15px;"><img src="/common/images/icon-arrowRight.gif" width="11" height="8" alt="" border="0">未选择</div>');
	});
}

function swapDtlTab(whichTab) {
	var path = '/common/images/';
	document.getElementById('product-features').style.display = 'none';
	document.getElementById('product-colors').style.display = 'none';
	document.getElementById('product-accessories').style.display = 'none';
	document.getElementById('product-cadSymbols').style.display = 'none';
	document.getElementById('features-tab').src = path + 'tab-productFeatures.gif';
	document.getElementById('colors-tab').src = path + 'tab-productColors.gif';
	document.getElementById('accessories-tab').src = path + 'tab-productAccessories.gif';
	document.getElementById('cad-tab').src = path + 'tab-productCadSymbols.gif';
	if(whichTab == 1) {
		document.getElementById('product-features').style.display = 'block';
		document.getElementById('features-tab').src = path + 'tab-productFeatures-on.gif';
	} else if(whichTab == 2) {
		document.getElementById('product-colors').style.display = 'block';
		document.getElementById('colors-tab').src = path + 'tab-productColors-on.gif';
	} else if(whichTab == 3) {
		document.getElementById('product-accessories').style.display = 'block';
		document.getElementById('accessories-tab').src = path + 'tab-productAccessories-on.gif';
	} else if(whichTab == 4) {
		document.getElementById('product-cadSymbols').style.display = 'block';
		document.getElementById('cad-tab').src = path + 'tab-productCadSymbols-on.gif';
	}
}

function swapTab(activeTab) {
	var imgName = '';
	var imgNameActive = '';
	for(var j=1; j<=4; j++) {
		document.getElementById('tabContent0' + j).style.display = 'none';
		imgName = document.getElementById('tab0' + j).src;
		if(imgName.indexOf('-on') > 0) {
			var imgName_array = imgName.split("-on");
			document.getElementById('tab0' + j).src = imgName_array[0] + imgName_array[1];
		}
	}
	imgNameActive = document.getElementById('tab0' + activeTab).src;
	var imgNameActive_array = imgNameActive.split(".gif");
	document.getElementById('tab0' + activeTab).src = imgNameActive_array[0] + '-on.gif';
	document.getElementById('tabContent0' + activeTab).style.display = 'block';
}

//
// on DOM-load events
//
$(function() { 
	
	// Round Corners
	$("div.roundedCorners").corner("round 6px");
	
	//Not Selected
	callNotSelected('div.notSelected');
	
	// Lightbox initiated and icon applied
	callLightbox('a.lightbox');
	callLightboxDtl('a.lightbox-dtl');
	
	// Lightbox initiated, no icon needed
	$('a.lightbox-hc').lightBox();
	
	// Populates Wehre to Buy Pull downs
	if ($("#province")[0]) {
        // Set the onchange event of the 'states' dropdown to call the ajax function that
        // populates the cites select.  This is in the global util nav.
        $("#province").change(
              function() {
                  getCitiesForState('#province', '#city', 'STORES');
              }
         );
    }
    
    if($("#logo-tools")[0]) {
        $("#logo-tools").html(toolButtons);
	}

});


function openWindow(theURL,windowName,features) {
    window.open(theURL,windowName,features);
}

function openWhereToBuyStoreTypeWindow() {
    var my_window = window.open('', 'storeTypeWindow', "status=1,width=350,height=150");
    my_window.document.write('<strong>零售店</strong>是代表优雅生活的科勒全线产品向消费者展示和销售的地方，就近消费十分方便。<br /><strong>大卖场</strong>是销售科勒产品的各大家居卖场，家居卖场的价格优势和经典厨卫产品在此完美结合。<br /><strong>旗舰店</strong>是各个地区面积较大，产品陈列十分齐全的科勒零售店，多含进口产品。倘佯其中，全方位感触优雅生活。');
}

// just about every page in the site has compare
var compareWindow = null;
var videoWindow = null; // videos popup