var imgArray;
var swtch = 1;
var flag = 1;
var current = "none";
var alternates;
var colors
var images
var ids
var color_sizes
var array1 = new Array(); //holds the colors
var array2 = new Array(); //holds the corresponding sizes
var originalPrice;
var zoomflag = 0;
var origUrl = "";
var boxcolors;
var hex;
window.onload = prepLinks;

function prepLinks(){
	if (!document.getElementsByTagName) return false;
	
	if (document.pre_id){
		document.pre_id.email_address.onfocus = function(){
			return clearText();
		}
	}
	if (document.forms['checkoutform']){
		countryForm(document.forms['checkoutform'].country.value, 'billing');
		countryForm(document.forms['checkoutform'].shp_country.value, 'shipping');
	}
	
	if ( document.forms['cc_info'] ){
		
		document.getElementById('cc_option').checked = false;
		document.getElementById('pp_option').checked = false;
		
		
		if ( document.forms['cc_info'].pay_options.value != 'credit_card'  ){
			toggleCC(true);
		}
		document.getElementById('pp_half').style.display = 'none';
	}
	
	var url = document.URL;
	var urlitems = url.split("/");
	if (document.forms['product']){
		if (url.match('https://') == null){
			if (url.match('www.') != null){
				makeRequest("http://www.ktcollection.com/xml_images.php?sku="+urlitems[7]+"");
			} else {
				makeRequest("http://ktcollection.com/xml_images.php?sku="+urlitems[7]+"");
			}
		
		
			if (document.forms['product']){
				if ( (document.forms['product'].item_color) && (document.forms['product'].item_size) ){
					if (url.match('www.') != null){
						sizeRequest("http://www.ktcollection.com/xml_sizes.php?sku="+urlitems[7]+"");
					} else {
						sizeRequest("http://ktcollection.com/xml_sizes.php?sku="+urlitems[7]+"");
					}
				}
			}
		}
	}
	
	
	if (document.forms['product']){
		if (document.forms['product'].item_color){
			//get color and hex codes from the database
			//colRequest("http://www.ktcollection.com/xml_colors.php?sku="+urlitems[7]+"");
			
			var colorMenu = document.forms['product'].item_color;
			colorMenu.onchange = function(){
				if (document.forms['product'].item_size){
					return doBoth(colorMenu.options[this.selectedIndex].value, urlitems[7])
				} else {
					return changeColor(colorMenu.options[this.selectedIndex].value);
				}
				
			}
			
		}
	}
	
	if (document.forms['product']){
		if (document.forms['product'].option){
			originalPrice = document.getElementById("price").firstChild.data;
			var option_box = document.forms['product'].option;
			option_box.onclick = function(){
				changePrice(option_box.value, option_box.checked)
			}
		}
	}
	
	if (document.forms['search_form']){
		var search_input = document.forms['search_form'].search;
		search_input.onfocus = function(){
			return setValue(this, '');
		}
	}
	
	if (document.forms['stores']){
		var store_state = document.forms['stores'].state;
		store_state.onchange = function(){
			return changeState(this.value);
		}
	}
	
	var links = document.getElementsByTagName("a");
	for ( var i=0; i < links.length; i++) {
		if (links[i].className == "cal" || links[i].className == 'help'){
			links[i].onclick = function() {
				return popup(this, 400, 400);
			}
		}
		if (links[i].className == "zoom"){
			links[i].onclick = function() {
				return popup(this, 800, 710);
			}
		}
		
		if (links[i].className == "email"){
			links[i].onclick = function(){
				return newIframe(this.href);
			}
		}
		
		if ( links[i].className == 'press_link' ){
			links[i].onclick = function(){
				return showNews(this);
			}
		}
		
	}
	
	if (document.getElementById("views")){
		var views = document.getElementById("views");
		alternates = views.getElementsByTagName("a");
	
		for (var i=0; i<alternates.length; i++){
			if (alternates[i].className == "alternate" || alternates[i].className == "original"){
				alternates[i].onclick = function(){
					return changeImg(this);
				}
			}
		}
	}
	
	if (document.getElementById("thumb_box")){
		var views = document.getElementById("thumb_box");
		alternates = views.getElementsByTagName("a");
	
		for (var i=0; i<alternates.length; i++){
			if (alternates[i].className == "alternate" || alternates[i].className == "original"){
				alternates[i].onclick = function(){
					return changeImg(this);
				}
			}
		}
	}
}

function makeRequest(url) {
        var http_request = false;

        if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            http_request = new XMLHttpRequest();
            if (http_request.overrideMimeType) {
                http_request.overrideMimeType('text/xml');
                // See note below about this line
            }
        } else if (window.ActiveXObject) { // IE
            try {
                http_request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }

        if (!http_request) {
            unLink();
            return false;
        }
        http_request.onreadystatechange = function() { alertContents(http_request); };
        http_request.open('GET', url, true);
        http_request.send(null);

}

function sizeRequest(url){
	var http_request = false;
	if (window.XMLHttpRequest) { // Mozilla, Safari, ...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
			// See note below about this line
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	
	if (!http_request) {
            unLink();
            return false;
        }
        http_request.onreadystatechange = function() { alertSizes(http_request); };
        http_request.open('GET', url, true);
        http_request.send(null);
}

function alertContents(http_request) {

        if (http_request.readyState == 4) {
            if (http_request.status == 200) {
               	var xmldoc = http_request.responseXML;
				colors = xmldoc.getElementsByTagName('color');
				images = xmldoc.getElementsByTagName('image');
				ids = xmldoc.getElementsByTagName('id');
            } else {
                alert('There was a problem with the request.');
            }
        }
}

function alertSizes(http_request) {

        if (http_request.readyState == 4) {
            if (http_request.status == 200) {
               	var xmldoc = http_request.responseXML;
				var size_colors = xmldoc.getElementsByTagName('color');
				for (var a=0; a < size_colors.length; a++){
					array1.push(size_colors[a].getAttribute("name"));
					var sizes = size_colors[a].getElementsByTagName('size');
					var sizeHolder = new Array();
					for (var c=0; c<sizes.length; c++){
						sizeHolder.push(sizes[c].firstChild.data)
					}
					array2.push(sizeHolder);
				}
            } else {
                alert('There was a problem with the request.');
            }
        }
}

function changeImg(url, id)
{
	var imgSrc = url+"";
	if ( id != null || id != '' ){
		var id_text = '&id='+id;
	}
	if (document.getElementById("picholder")){
		var picholder = document.getElementById("picholder");
	} else {
		var picholder = document.getElementById("press_pic");
	}
	if (current == "none"){
		current = alternates[0].href;
	}
	if (flag == 1){
		flag = 0;
		//create a new link
		var newlink = document.createElement('a');
		newlink.setAttribute('class', 'zoom');
		newlink.onclick = function() {
			return popup(this, 800, 710);
		}
		if (current != imgSrc){
			if (swtch == 1){
				if ( document.getElementById('fullsize') ){
					var full1 = document.getElementById('fullsize');
					var href = full1.parentNode.getAttribute('href');
					if (href != null){
						var urlarray = href.split('&');
						newlink.setAttribute('href', urlarray[0]+id_text);
					}
				}
				if ( document.getElementById('fullsize2') ){
					var removeme = document.getElementById('fullsize2');
					removeme.parentNode.removeChild(removeme);
				}
				var newimg = new Image();
				newimg.onload = function(){	
					var pic = document.createElement("img");
					pic.setAttribute("id", "fullsize2");
					pic.setAttribute("src", imgSrc);
					pic.setAttribute("alt", "");
					setOpacity(pic, 0);
					newlink.appendChild(pic);
					picholder.appendChild(newlink);
					fadein("fullsize2", 0);
					fadeout("fullsize", 100);
				}
				newimg.src = url;
				swtch = 2;
			} else {
				if ( document.getElementById('fullsize2') ){
					var full1 = document.getElementById('fullsize2');
					var href = full1.parentNode.getAttribute('href');
					if (href != null){
						var urlarray = href.split('&');
						newlink.setAttribute('href', urlarray[0]+id_text);
					}

				}
				if ( document.getElementById('fullsize') ){
					var removeme = document.getElementById('fullsize');
					removeme.parentNode.removeChild(removeme);
				}
				var newimg2 = new Image();
				newimg2.onload = function(){	
					var pic2 = document.createElement("img");
					pic2.setAttribute("id", "fullsize");
					pic2.setAttribute("src", imgSrc);
					pic2.setAttribute("alt", "");
					setOpacity(pic2, 0);
					newlink.appendChild(pic2);
					picholder.appendChild(newlink);
					fadein("fullsize", 0);
					fadeout("fullsize2", 100);
				}
				newimg2.src = url;
				swtch = 1;
			} 
			current = imgSrc;
		} else if (current == imgSrc){
			flag = 1;
		}
	}
	return false;
}

function changeColor(selected_color){
	for (var i=0; i<colors.length; i++){
		if (selected_color == colors[i].firstChild.data){
			if (current == "none"){
				the_img = document.getElementById("fullsize");
				current = the_img.src;
			}
			changeImg("http://ktcollection.com/images/fullsize/"+images[i].firstChild.data+"", ids[i].firstChild.data);
			
			if (ids[i] != ""){
				changeId(ids[i].firstChild.data);
			}
		}
	}
}

function changeId(id){
	
	var zoomdiv = document.getElementById('picholder');
	var zoomlinks = zoomdiv.getElementsByTagName('a');
	for (var x=0; x<zoomlinks.length; x++){
		if (zoomlinks[x].className == "zoom"){
			var currenturl = zoomlinks[x].getAttribute("href");
			if (zoomflag == 0){
				origUrl = currenturl;
				zoomflag = 1;
			}
			var newurl = origUrl+"&id="+id+"";
			zoomlinks[x].setAttribute("href", newurl);
		}
	}
}

function setOpacity(obj, opacity) {
	//opacity = (opacity == 100)?99.999:opacity;
	// IE/Win
	obj.style.filter = "alpha(opacity:"+opacity+")";
	// Safari<1.2, Konqueror
	obj.style.KHTMLOpacity = opacity/100;
	// Older Mozilla and Firefox
	obj.style.MozOpacity = opacity/100;
	// Safari 1.2, newer Firefox and Mozilla, CSS3
	obj.style.opacity = opacity/100;
}

function fadein(objId,opacity) {
	if (document.getElementById) {
		obj = document.getElementById(objId);
		
		if (opacity == 0){
			obj.style.visibility = "visible";
		}
		
		if (opacity <= 100) {
			setOpacity(obj, opacity);
			opacity += 20;
			window.setTimeout("fadein('"+objId+"',"+opacity+")", 100);
		} else if (opacity > 100){
			flag = 1;
		}
	}
}

function fadeout(objId,opacity) {
	if (document.getElementById(objId)) {
		obj = document.getElementById(objId);

		if (opacity <= 0){
			//obj.style.visibility = "hidden";
			if (document.getElementById("picholder")){
				var picholder = document.getElementById("picholder");
			} else {
				var picholder = document.getElementById("press_pic");
			}	
			var trash = picholder.getElementsByTagName("img");
			//picholder.removeChild( obj );
			/*for (var d=0; d<trash.length; d++){
				alert( trash[d].getAttribute('id') + objId );
				if (trash[d].getAttribute('id') == objId){
					picholder.removeChild(trash[d]);
					alert('removing '+objId);
				}
			}*/			
		}
		
		if (opacity >= 0) {
			setOpacity(obj, opacity);
			opacity = opacity - 20;
			window.setTimeout("fadeout('"+objId+"',"+opacity+")", 100);
		}
	}
}

function updateSizes(color){	
	if (color != ""){
		var sizeMenu = document.forms['product'].item_size;
		var sizeOptions = document.forms['product'].item_size.options;
		sizeOptions.length = 0;
		var newOption = document.createElement("option");
		newOption.setAttribute("value", "");
		var text = document.createTextNode("---Size---");
		newOption.appendChild(text);
		sizeMenu.appendChild(newOption);
		
		var index = searchItem(color, array1);
		
		for (var x=0; x < array2[index].length; x++){
			var newOption = document.createElement("option");
			newOption.setAttribute("value", array2[index][x]);
			var text = document.createTextNode(array2[index][x]);
			newOption.appendChild(text);
			sizeMenu.appendChild(newOption);
		}
	}
	
}

function changePrice(price, trueFalse)
{
	var priceDiv = document.getElementById("price");
	if (trueFalse){
		priceDiv.firstChild.data = "$"+price+"";
	} else {
		priceDiv.firstChild.data = originalPrice;
	}
	
	flashDiv('price');
}

function newIframe(url)
{
	if (!(document.getElementById("framediv"))){
		var frameDiv = document.createElement("div");
		frameDiv.setAttribute("id", "framediv");
		
		var close_box = document.createElement("img");
		close_box.setAttribute("id", "close");
		close_box.setAttribute("src", "/images/close.jpg");
		close_box.setAttribute("alt", "");
		close_box.setAttribute("title", "Close");
		close_box.onclick = function(){
			main.removeChild(frameDiv);
		};
		close_box.onload = function(){
			frameDiv.appendChild(close_box);
		};
		close_box.src="/images/close.jpg";
		
		var iframe = document.createElement("iframe");
		iframe.setAttribute("src", url); 
		iframe.setAttribute("width", "100%");
		iframe.setAttribute("height", "100%");
		iframe.setAttribute("frameborder", "0");
		
		frameDiv.appendChild(iframe);
		var main = document.getElementById("main");
		main.appendChild(frameDiv);
	}
	return false;
}

function flashDiv(obj)
{
	changeBcgd (obj, '#F7EAA9');
	window.setTimeout("changeBcgd('"+obj+"', 'transparent')", 500);
	window.setTimeout("changeBcgd('"+obj+"', '#F7EAA9')", 900);
	window.setTimeout("changeBcgd('"+obj+"', 'transparent')", 1300);
}

function changeBcgd (obj, color)
{
	var div = document.getElementById(obj);
	div.style.backgroundColor = color;
}

function searchItem(value, thearray){
	var index = -1;
	for (var n=0; n<thearray.length; n++){
		if (value == thearray[n]){
			index = n;
		}
	}
	return index;
}

function doBoth (color, sku){
	changeColor(color);
	updateSizes(color);
}

function popup(url, width, height){
	rdPop = window.open(url, "dateWin", "width="+width+", height="+height+", status=no, resizable=no, scrollbars=1");
	rdPop.focus();
	return false;
}

function clearText(){
	document.pre_id.email.value= "";
}

function addText(text){
	document.pre_id.email.value= text;
}

function PrePopulate(form)
{
  if (form.same_add.checked) {
    if (form.shp_first_name){
    	form.shp_first_name.value = form.first_name.value;
    }
    if (form.shp_last_name){
	    form.shp_last_name.value = form.last_name.value;
	}
    form.shp_address.value = form.address.value;
    form.shp_address2.value = form.address2.value;
    form.shp_city.value = form.city.value;
    form.shp_state.value = form.state.value;
    form.shp_zip.value = form.zip.value;
    form.shp_country.value = form.country.value;
    form.shp_postal_code.value = form.postal_code.value;
    form.shp_province.value = form.province.value;
    
    countryForm(form.shp_country.value, 'shipping')
    
    } else {
    form.shp_first_name.value = '';
    form.shp_last_name.value = '';
    form.shp_address.value = '';
    form.shp_city.value = '';
    form.shp_state.value = '';
    form.shp_zip.value = '';
    form.shp_country.value = '';
    form.shp_postal_code.value = '';
    form.shp_province.value = '';
	form.shp_address2.value = '';
    }
}

function countryForm(value, type){
	//zip, province, postal code
	if (type == 'billing'){
		if (value == 'CA'){
			document.getElementById('zip').style.display = 'none';
			document.getElementById('province').style.display = 'block';
			document.getElementById('postal_code').style.display = 'block';
			document.getElementById('state').style.display = 'none';
			insertAsterisk('bill');
		} else if (value == 'US'){
			document.getElementById('zip').style.display = 'block';
			document.getElementById('province').style.display = 'none';
			document.getElementById('postal_code').style.display = 'none';
			document.getElementById('state').style.display = 'block';
			removeAsterisk('bill');
		} else {
			document.getElementById('zip').style.display = 'none';
			document.getElementById('province').style.display = 'none';
			document.getElementById('postal_code').style.display = 'block';
			document.getElementById('state').style.display = 'none';
			removeAsterisk('bill');
		}
	} else if (type == 'shipping'){
		if (value == 'CA'){
			document.getElementById('shp_zip').style.display = 'none';
			document.getElementById('shp_province').style.display = 'block';
			document.getElementById('shp_postal_code').style.display = 'block';
			document.getElementById('shp_state').style.display = 'none';
			insertAsterisk('ship');
		} else if (value == 'US'){
			document.getElementById('shp_zip').style.display = 'block';
			document.getElementById('shp_province').style.display = 'none';
			document.getElementById('shp_postal_code').style.display = 'none';
			document.getElementById('shp_state').style.display = 'block';
			removeAsterisk('ship');
		} else {
			document.getElementById('shp_zip').style.display = 'none';
			document.getElementById('shp_province').style.display = 'none';
			document.getElementById('shp_postal_code').style.display = 'block';
			document.getElementById('shp_state').style.display = 'none';
			removeAsterisk('ship');
		}
	}
}

function insertAsterisk (type){
	if (type == 'bill'){
		var ps_code = document.getElementById('postal_code');
		var labels = ps_code.getElementsByTagName('label');
		var ps_label = labels[0];
	} else if (type == 'ship'){
		var ps_code = document.getElementById('shp_postal_code');
		var labels = ps_code.getElementsByTagName('label');
		var ps_label = labels[0];
	}
	
	var req_span = document.createElement("span");
	req_span.setAttribute('class', 'req');			
	
	var asterisk = document.createTextNode(' *');
	req_span.appendChild(asterisk);
	ps_label.appendChild(req_span);
}

function removeAsterisk (type){
	if (type == 'bill'){
		var ps_code = document.getElementById('postal_code');
	} else if (type == 'ship'){
		var ps_code = document.getElementById('shp_postal_code');
	}
	var labels = ps_code.getElementsByTagName('label');
	var ps_label = labels[0];
	
	var req_spans = ps_label.getElementsByTagName('span');
	if (req_spans.length > 0){
		ps_label.removeChild(req_spans[0]);
	}
}

function changeState(state)
{
	window.location = 'includes/helper.php?state='+state;
}

function setValue(obj, text)
{
	obj.value = text;
}

function toggleCC(status)
{
	var cc_info = document.forms['cc_info'];
	cc_info.card_type.disabled = status;
	cc_info.card_number.disabled = status;
	cc_info.month.disabled = status;
	cc_info.year.disabled = status;
	cc_info.submit.disabled = status;
	
	if ( status == true ){
		document.getElementById('pp_half').style.display = 'block';
	} else {
		document.getElementById('pp_half').style.display = 'none';
	}
}

function showNews(link)
{
	
	if ( !document.getElementById('super') ){
		var url = link.href;
		var superDiv = document.createElement('div');
		superDiv.setAttribute('id', 'super');
				
		var img = new Image();
		img.onload = function(){	
			var pic = document.createElement('img');
			pic.setAttribute("src", url);
			pic.setAttribute("alt", "");
			superDiv.appendChild(pic);
			
			var close = document.createElement('p');
			close.setAttribute("id", 'press_close');
			
			var close_btn = document.createElement('img');
			close_btn.setAttribute("src", '/images/close.jpg');
			close_btn.setAttribute('alt', '');
			close_btn.setAttribute('title', 'close');
			
			close_btn.onclick = function (){
				superDiv.parentNode.removeChild(superDiv);
			}
			
			close.appendChild(close_btn);
			
			var dimensions = getWindowSize();
			var width = img.width;
			var leftPos = Math.round( (dimensions[0] - width) / 2  );
			var topPos = 75;

			
			superDiv.appendChild(close);
			superDiv.style.left = leftPos+'px';
			superDiv.style.top = topPos+'px';
			document.getElementById('main').appendChild(superDiv);
		}
		img.src = url;
	}
	return false;
}

function getWindowSize()
{
	var viewportwidth;
	var viewportheight;
	
	// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
	if (typeof window.innerWidth != 'undefined')
	{
		viewportwidth = window.innerWidth,
		viewportheight = window.innerHeight
	} else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0)
	{
		viewportwidth = document.documentElement.clientWidth,
		viewportheight = document.documentElement.clientHeight
	} else {
		viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
		viewportheight = document.getElementsByTagName('body')[0].clientHeight
	}
	
	return Array(viewportwidth, viewportheight);
}
