
var inmenu=false;
var lastmenu=0;
var seriesnum="";
var updateConfig = true;

	var dial_id = new Array ('euroclass','ammin','ammod','elquat','venus','saturn','rommin','quartet','mark','markdbl','markbld');
	var dial_I_id = new Array ('euroclass_I','ammod_I','elquat_I','quartet_I','mark_I','markdbl_I','markbld_I');
	var dial_full = new Array('Euro Classic','American Minute','American Modern','El Quatro','Venus','Saturn','Roman Minute','Quartet','Mark','Mark Double','Mark Bold');
	var dial_abbr = new Array('Euro','Am Min','Am Mod','El Q','Venus','Saturn','Rom Min','Quartet','Mark','Mark Dbl','Mark Bld');
	var arr_Dials = new Array(dial_id, dial_full, dial_abbr);
	var arr_series = new Array('1','2','3','4');
	var arr_series_roman = new Array('I','II','III','III Canister');
	var arr_textures = new Array('open','stucco','brick');
	var arr_menus = new Array('series','bkgd','dial','hands','size');

/**** Enable the following function to find errors in the javascript
    * window.onerror = function (err, file, line) {
    *   alert('The following error occured: ' + err + '\n' +
    *   'In file: ' + file + '\n' +
    *   'At line: ' + line);
    *   return true;
    * }
    **********************/

/* array.indexOf is not supported in IE6.  Instead, use the following 
 * function to find a value in an array and return its index
 */

function arrayIndex(arr,val) {
    len = arr.length;
	for (x = 0; x < len; x++) {
		if (arr[x] == val) return x;
	}
	return -1;
}

String.prototype.toProperCase = function() {return this.charAt(0).toUpperCase() + this.substring(1,this.length).toLowerCase();}
function toHex(v) { v=Math.round(Math.min(Math.max(0,v),255)); return("0123456789ABCDEF".charAt((v-v%16)/16)+"0123456789ABCDEF".charAt(v%16)); }
function toDec(v) {return ("0123456789ABCDEF".indexOf(v.substring(0,1)))*16+("0123456789ABCDEF".indexOf(v.substring(1,2))); }
function rgb2hex(r) { return(toHex(r[0])+toHex(r[1])+toHex(r[2])); }
function hex2rgb(r) { return [toDec(r.substring(0, 2)),toDec(r.substring(2, 4)),toDec(r.substring(4, 6))]; }
function left(str, n){
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}

function right(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}

function init() {
    initFields();
    fillConfiguratorData();
    var loadingDiv = document.getElementById("loading");
    loadingDiv.style.visibility = "hidden";
    var dlAllowed = document.getElementById("DownloadAllowed");
    if (dlAllowed.value == "true") {
        showForm("downloadCAD");
    }
}

function initFields() {
    var stateFieldRow = document.getElementById("stprStateRow");
    var provFieldRow = document.getElementById("stprProvRow");
    var provOtherFieldRow = document.getElementById("stprProvOtherRow");
    if (stateFieldRow.value == "") {stateField.style.display = "none";}
    if (provFieldRow.value == "") {provField.style.display = "none";}
    if (provOtherFieldRow.value == "") {provOtherField.style.display = "none";}
}

function saveImage() {
    window.open("clockimage.aspx", "Configurator", "width=590,height=480,titlebar,status=yes");
}

function printImage() {
    window.open("clockimg_print.aspx", "Configurator", "width=590,height=480,titlebar,status=yes");
}

function Menu(current) {
	if (!document.getElementById) {return;}
	inmenu=true;
	oldmenu=lastmenu;
	lastmenu=current;
	if (oldmenu) {Erase(oldmenu,false);}
	if ((current == "dial") && (getCookie('series') == "1")) {
		s1 = "_I";
	} else {
		s1 = "";
	}
	Twist(current,"open");
	box=document.getElementById("box_" + current + s1);
	box.style.visibility="visible";
}
function Erase(current,immediate) {
    if (arrayIndex(arr_menus,current) == -1) {return;}
	if (!document.getElementById) {return;}
	if (!immediate && inmenu && lastmenu==current) {
	 return;
	}
	Twist(current,"closed");
	m=document.getElementById("menu_" + current);
	if ((current == "dial") && (getCookie('series') == "1")) {
		s1 = "_I";
	} else {
		s1 = "";
	}
	box=document.getElementById("box_" + current + s1);
  box.style.visibility="hidden";
}

function Timeout(current,time) {
   inmenu=false;
   if (time == "") {time=2000;}
   window.setTimeout("Erase('" + current + "',false)",time) ;
}

function Stayopen() {
	inmenu=true;
}

function Twist(current,status) {
	if (status == "open") {
		arrow = "&#9658;";
	} else {
		arrow = "&#9660;";
	}
    twistie = document.getElementById("t_" + current);
    twistie.innerHTML = arrow;
}
function toggleCells(el){
	rCells=document.getElementsByTagName('div');
	for (i = 0; i < rCells.length; i++) {
		if (rCells[i].className=='ccellSel') {
			rCells[i].className='ccell';
		}
		el.className='ccellSel';
	}
	setCookie('colorcell',el.id,7);
	ChgBackColor(el.style.backgroundColor);
}
function movepic(img_name,img_src) {
	document[img_name].src=img_src;
}
function ChgClockSeries(seriesnum) {
	if (seriesnum !== "") {
		setCookie("series",seriesnum,7);
		dial = getCookie('dial');
		disallowed = new String("_ammin_rommin_venus_saturn");
		if ((disallowed.indexOf(dial) > 0) && (seriesnum == '1')) {
			dial = "";
			delCookie('dial');
		}
		enableDials(seriesnum);
		bo = document.getElementById("bkgd_open");
		//if (seriesnum == '1') {
		//if (seriesnum != '2') {
		// seriesnum 4 does not exist, using it just to hide the open background no matter which is selected.
		// apparently not being used at all at the moment...
		if (seriesnum != '4') {
			ChgBackTexture(getCookie('texture'));
			bo.style.visibility = "hidden";
		} else {
			bo.style.visibility = "";
		}
		bs=document.getElementById("box_side_img");
		si=document.getElementById("choice_series_icon");
		st=document.getElementById("choice_series_text");
		for (s in arr_series) {
			thumb=document.getElementById("thumb_series" + arr_series[s]);
			cap=document.getElementById("cap_series" + arr_series[s]);
			if (arr_series[s] == seriesnum) {
				thumb.style.border = "2px solid #000";
				cap.style.fontWeight = "bold";
			} else {
				thumb.style.border = "1px solid #999";
				cap.style.fontWeight = "normal";
			}
		}
		bs.src = "/images/configurator/series/series" + seriesnum + ".png";
		si.src = "/images/configurator/series/thumb_series" + seriesnum + ".gif";
		st.innerHTML = "Series&nbsp;" + arr_series_roman[seriesnum - 1];
		checkConfigurationDone("CAD");
	} else {
		disableDials();
	}
}

function ChgBackColor(color){
	if (color !== "") {
	    if (color.length == 7) {
	        hexvals = hex2rgb(right(color.toUpperCase(),6));
	        color = "rgb(" + hexvals + ")";
	    }
		bf=document.getElementById("box_front");
		ci=document.getElementById("choice_bkgd_icon");
		cb=document.getElementById(getCookie('colorcell'));
		bf.style.backgroundColor = color;
		ci.style.backgroundColor = color;
		cb.className = "ccellSel";
		setCookie("bgcolor",color,7);
		checkConfigurationDone("ALL");
	}
}

function ChgBackTexture(texture){
	if (texture !== "") {
		bf=document.getElementById("box_front_texture");
		ci=document.getElementById("choice_bkgd_icon");
		bt=document.getElementById("choice_bkgd_text");
		// ?? not sure how this would happen if that option is only available to series 4
		//if (!((getCookie('series') != "2") && (texture == 'open'))) {
		//if (true) {
			for (t in arr_textures) {
				thumb=document.getElementById("thumb_" + arr_textures[t]);
				cap=document.getElementById("cap_" + arr_textures[t]);
				if (arr_textures[t] == texture) {
					thumb.style.border = "2px solid #000";
					cap.style.fontWeight = "bold";
				} else {
					thumb.style.border = "1px solid #999";
					cap.style.fontWeight = "normal";
				}
			}
			bf.src = "/images/configurator/bkgd_" + texture + ".png";
			ci.src = "/images/configurator/choice_bkgd_" + texture + ".png";
			bt.innerHTML = texture;
			setCookie("texture",texture,7);
		//} else {
			//bf.src = "/images/configurator/bkgd_plain.png";
			//ci.src = "/images/configurator/select_bkgd.gif";
			//bt.innerHTML = "";
			//delCookie("texture");
			//clearThumbs("texture");
		//}
		checkConfigurationDone("ALL");
	}
}
function ChgClockDial(dial,seriesnum) {
	if (seriesnum === "") {
		seriesnum = getCookie("series");
		if (seriesnum === "") {return "";}
	}
	if (seriesnum == '1') {
		dmod = "_I";
		arr_d = dial_I_id
	} else {
		dmod = "";
		arr_d = dial_id;
	}
	df=document.getElementById("clock_dial");
	cb=document.getElementById("clock_back");
	di=document.getElementById("choice_dial_icon");
	dt=document.getElementById("choice_dial_text");
	if (dial != "") {
		for (d in arr_d) {
			thumb=document.getElementById("thumb_" + arr_d[d]);
			cap=document.getElementById("cap_" + arr_d[d]);
			if (arr_d[d] == dial + dmod) {
				thumb.style.border = "2px solid #000";
				cap.style.fontWeight = "bold";
				fulldial = dial_full[d];
			} else {
				thumb.style.border = "1px solid #999";
				cap.style.fontWeight = "normal";
			}
		}
		df.src = "/images/configurator/dials/" + dial + ".png";
		if (seriesnum != "1") {
			cb.src = "/images/configurator/dials/dial_ring.png";
		} else {
			cb.src = "/images/blank2.gif";
		}
		di.src = "/images/configurator/dials/thumb_" + dial + ".png";
		dt.innerHTML = fulldial;
		//dt.innerHTML = dial;
		setCookie("dial",dial,7);
	} else {
		df.src = "/images/blank2.gif";
		cb.src = "/images/blank2.gif";
		di.src = "/images/configurator/select_dial.gif";
		dt.innerHTML = "";
		delCookie('dial');
		clearThumbs('dial' + dmod);
	}
	checkConfigurationDone("CAD");
}
function clearThumbs(thumbtype) {
	mod = "";
	var the_array = new Array();
	switch (thumbtype) {
		case 'dial':
			the_array = dial_id;
			break;
		case 'dial_I':
			the_array = dial_I_id;
			break;
		case 'texture':
			the_array = arr_textures;
			break;
		case 'series':
			the_array = arr_textures;
			mod = "series";
			break;
		default:
	}
	for (x in the_array) {
		thumb=document.getElementById("thumb_" + mod + the_array[x]);
		cap=document.getElementById("cap_" + mod + the_array[x]);
		thumb.style.border = "1px solid #999";
		cap.style.fontWeight = "normal";
	}
}

function disableDials() {
	dmd = document.getElementById('menu_dial_disabled');
	dm = document.getElementById('menu_dial');
	dmd.style.visibility = 'visible';
	dm.style.visibility = 'hidden';
	df=document.getElementById("clock_dial");
	df.src = "/images/blank.gif";
}

function enableDials(seriesnum) {
	dmd = document.getElementById('menu_dial_disabled');
	dm = document.getElementById('menu_dial');
	dmd.style.visibility = 'hidden';
	dm.style.visibility = 'visible';
	ChgClockDial(getCookie("dial"),seriesnum);
}

function ChgClockHands(handsnum) {
	if (handsnum != "") {
		var arr_hands = new Array('1','2','3','4','5','6','7','8','9','10');
		df=document.getElementById("clock_hands");
		di=document.getElementById("choice_hands_icon");
		dt=document.getElementById("choice_hands_text");
		for (h in arr_hands) {
			thumb=document.getElementById("thumb_h" + arr_hands[h]);
			cap=document.getElementById("cap_h" + arr_hands[h]);
			if (arr_hands[h] == handsnum) {
				thumb.style.border = "2px solid #000";
				cap.style.fontWeight = "bold";
			} else {
				thumb.style.border = "1px solid #999";
				cap.style.fontWeight = "normal";
			}
		}
		df.src = "/images/configurator/hands/h" + handsnum + ".png";
		di.src = "/images/configurator/hands/thumb_h" + handsnum + ".png";
		dt.innerHTML = "Hands " + handsnum;
		setCookie("hands",handsnum,7);
		checkConfigurationDone("CAD");
	}
}
function ChgClockSize(size) {
	if (size != "") {
		var arr_sizes = new Array('3','4','5','6','7','8');
		//var arr_sizes = new Array('3','4','5','6','7','8','9');
		zt=document.getElementById("choice_size_text");
		zt.innerHTML = size + " foot";
		for (z in arr_sizes) {
			cap=document.getElementById("cap_z" + arr_sizes[z]);
			if (arr_sizes[z] == size) {
				cap.style.border = "2px solid #000";
			} else {
				cap.style.border = "1px solid #999";
			}
		}
		setCookie("size",size,7);
		checkConfigurationDone("CAD");
	}
}

function setCookie(c_name,value,expiredays) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookie(c_name) {
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    { 
    c_start=c_start + c_name.length+1; 
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    } 
  }
return "";
}

function delCookie(c_name) {
	if (getCookie(c_name)) {
		document.cookie = c_name + "=;expires=Thu, 01-Jan-1970 00:00:01 GMT";
	}
}
function fillConfiguratorData() {
    updateConfig = false;
	ChgClockSeries(getCookie("series"));
	//ChgClockDial(getCookie("dial"));
	ChgClockHands(getCookie("hands"));
	ChgBackColor(getCookie("bgcolor"));
	ChgBackTexture(getCookie("texture"));
	ChgClockSize(getCookie("size"));
	updateConfig = true;
	checkConfigurationDone("ALL");
}
function clearData() {
	var answer=confirm("Delete current configuration and start over?");
	if (answer) {
		delCookie("series");
		delCookie("dial");
		delCookie("hands");
		delCookie("bgcolor");
		delCookie("texture");
		delCookie("size");
		delCookie("colorcell");
		location.reload(true);
	}
}
function checkConfigurationDone(configType) {
    if (updateConfig == false) return;
	restartButton = document.getElementById("button_restart");
	restartButton.style.visibility = "visible";
	doneForCAD = true;
	doneForALL = true;
	cadButton = document.getElementById("button_download");
	boxButtons = document.getElementById("box_buttons");
	vSeries = getCookie("series");
	vTexture = getCookie("texture");
	vbgColor = getCookie("bgcolor");
	vDial = getCookie("dial");
	vHands = getCookie("hands");
	vSize = getCookie("size");
	if ((vSeries == "") || (vDial == "") ||	(vHands == "") ||	(vSize == "")) {
		doneForCAD = false;
	}
	if ((vTexture == "") || (doneForCAD == false)) {
		doneForALL = false;
	}
	if (doneForCAD == true) {
	    buildCADFile();
		cadButton.style.visibility = "visible";
	} else {
		cadButton.style.visibility = "hidden";
	}
	if (doneForALL == true ) {
		updateConfigurationText();
		boxButtons.style.visibility = "visible";
	} else {
		boxButtons.style.visibility = "hidden";
	}
	var tafurl = location.protocol + "//" + location.host + "/configurator/viewclock.aspx?";
    tafurl += "b=" + getCookie("bgcolor");
	tafurl += "&c=" + getCookie("colorcell");
	tafurl += "&d=" + getCookie("dial");
	tafurl += "&h=" + getCookie("hands");
	tafurl += "&s=" + getCookie("series");
	tafurl += "&t=" + getCookie("texture");
	tafurl += "&z=" + getCookie("size");
    tafb = document.getElementById("TAFBuilder");
	tafb.value = tafurl;
	if (vSeries == "") {
	    Menu("series");
	} else if (vTexture == "") {
	    Menu("bkgd");
	} else if (vbgColor == "") {
	    Menu("bkgd");
	} else if (vDial == "") {
	    Menu("dial");
	} else if (vHands == "") {
	    Menu("hands");
	} else if (vSize == "") {
	    Menu("size");
    } else {
        Erase(lastmenu,true);
    }
}
function updateConfigurationText() {
	vDialNum = arrayIndex(dial_id,getCookie("dial"));
	vDialFull = dial_full[parseInt(vDialNum)];
	serNum = arr_series_roman[parseInt(vSeries) - 1];
	configBox = document.getElementById("config_text");
	configBox.style.color = "#000";
	configText = "<strong>Clock</strong>: Series " + serNum + "<br />";
	configText += "<strong>Hands</strong>: Style #" + vHands + "<br />";
	configText += "<strong>Size</strong>: " + vSize + " ft.<br />";
	configText += "<strong>Dial</strong>: " + vDialFull + "<br />";
	configText += "<strong>Background</strong>: " + vTexture.toProperCase();
	configBox.innerHTML = configText;
}
function showForm(formname) {

	if (lastmenu != "") Erase(lastmenu,true);
	dlg = document.getElementById("box_dialog");
	if (formname == "requestCAD") {
	    c_cad = getCookie('CADDLAllowed');
	    if (c_cad != "") {
	        var dlAllowed = document.getElementById("DownloadAllowed");
	        dlAllowed.value = "true";
	        document.forms[0].submit();
	        return;
	    }
	    countryField = document.getElementById("countries");
	    if (!countryField.value) {
	    country = "";
	    } else {
	    country = countryField.value;
	    }
	    checkCountry(country);
	}
    frm = document.getElementById("dlg_" + formname);
	dlg.style.visibility = "visible";
	frm.style.visibility = "visible"
}
function clearForm(form) {
    var arrElements = new Array(
        "box_dialog",
        "dlg_" + form,
        "friendemailreq",
        "youremailreq",
        "cadnamereq",
        "cademailreq",
        "request_granted",
        "cadcompanyreq",
        "cadaddressreq",
        "countriesreq",
        "cadcityreq",
        "cadstprreq",
        "cadzipreq",
        "cadphonereq"
    );
    for (el in arrElements) {
        if (document.getElementById(arrElements[el])) {
            document.getElementById(arrElements[el]).style.visibility = "";
        }
    }

}
function buildCADFile() {
	vSeries = getCookie("series");
	vDialNum = arrayIndex(dial_id,getCookie("dial"));
	vHands = getCookie("hands");
	vSize = getCookie("size");
	var ser_arr_num = new Array('I','II','III','III Can');
	var ser_arr_name = new Array('SMN','SMD','OMD','OMD CAN');
	serNum = ser_arr_num[parseInt(vSeries) - 1];
	serName = ser_arr_name[parseInt(vSeries) - 1];
	dialFull = dial_full[parseInt(vDialNum)];
	dialAbbr = dial_abbr[parseInt(vDialNum)];
	dirSeries = serNum + " - " + serName;
	if (dirSeries == 'III Can - OMD CAN') {
	    dirSeries = 'III - OMD CAN'; // hack to overcome odd naming convention.
	}
	dirDial = dialFull + " " + serNum;
	dirHands = dialFull + " " + serNum + " H" + vHands;
	fileName = vSize + "ft " + dialFull + " " + serNum + " H" + vHands;
	filePath = dirSeries + "/" + dirDial + "/" + dirHands + "/" + fileName;
	var fieldCADFileName = document.getElementById('CADFileName');
	var fieldCADPath = document.getElementById('CADPath');
	fieldCADFileName.value = fileName;
	fieldCADPath.value = filePath;
}

function popConfigurator() {
		loadingdiv = document.getElementById("loading");
    	cerrordiv = document.getElementById("cookieerror");
	    perrordiv = document.getElementById("popuperror");
		loadingdiv.style.visibility = "hidden";
    	cerrordiv.style.visibility = "hidden";
	    perrordiv.style.visibility = "hidden";
	if (popupblocked) {
	    perrordiv.style.visibility = "visible";
	} else if (nocookies){
	    cerrordiv.style.visibility = "visible";
	} else {
		loadingdiv.style.visibility = "visible";
    	window.open("configurator.aspx", "Configurator", "width=760,height=540,titlebar,status=yes");
		window.location.href = "/tower_clocks";
	}
}

function launchConfigurator() {
	window.open("configurator.aspx", "Configurator", "width=760,height=540,titlebar,status=yes");
	window.location.href = "/tower_clocks";
}

function getData() {
    b = decodeURIComponent(getQueryString("b"));
    s = getQueryString("s");
    c = getQueryString("c");
    t = getQueryString("t");
    z = getQueryString("z");
    d = getQueryString("d");
    h = getQueryString("h");
	if (b != "") {setCookie('bgcolor',b,7);}
	if (s != "") {setCookie('series',s,7);}
	if (c != "") {setCookie('colorcell',c,7);}
	if (t != "") {setCookie('texture',t,7);}
	if (z != "") {setCookie('size',z,7);}
	if (d != "") {setCookie('dial',d,7);}
	if (h != "") {setCookie('hands',h,7);}
}

function getQueryString(variable) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split("=");
		if (pair[0] == variable) {
			return pair[1];
		}
	}
	return "";
}

function checkCountry(country) {
    switch (country) {
        case "US":
            showSTPR("state");
            break;
        case "CA":
            showSTPR("prov");
            break;
        case "XX":
            showSTPR("nothing");
            break;
        default: 
            showSTPR("prov_other");
    }
}

function showSTPR(fld) {
    if (fld == "") {return;}
    var stprLabel = document.getElementById("stprLabel");
    var stateField = document.getElementById("states");
    var provField = document.getElementById("provinces");
    var provOtherField = document.getElementById("prov_other");
    var stateFieldRow = document.getElementById("stprStateRow");
    var provFieldRow = document.getElementById("stprProvRow");
    var provOtherFieldRow = document.getElementById("stprProvOtherRow");
    stateFieldRow.style.display = "none";
    provFieldRow.style.display = "none";
    provOtherFieldRow.style.display = "none";
    switch (fld) {
        case "state":
            stateFieldRow.style.display = "";
            provField.value = "";
            provOtherField.value = "";
            stprLabel.innerHTML = "State:"
            updateSTPR("","");
            break;
        case "prov":
            provFieldRow.style.display = "";
            stateField.value = "";
            provOtherField.value = "";
            stprLabel.innerHTML = "Province:"
            updateSTPR("","");
            break;
        case "prov_other":
            provOtherFieldRow.style.display = "";
            provField.value = "";
            stateField.value = "";
            provOtherField.value = "";
            stprLabel.innerHTML = "Province:"
            updateSTPR("XX","");
            break;
        default:
            provField.value = "";
            stateField.value = "";
            provOtherField.value = "";
            stprLabel.innerHTML = "State/Province:"
            updateSTPR("","");
            
    }
}

function updateSTPR(val, def) {
    var stprActual = document.getElementById("stprActual");
    if (val == '') {val = def;}
    stprActual.value = val;
}