var ns4 = document.layers;
var op5 = (navigator.userAgent.indexOf("Opera 5")!=-1)||(navigator.userAgent.indexOf("Opera/5")!=-1);
var op6 = (navigator.userAgent.indexOf("Opera 6")!=-1)||(navigator.userAgent.indexOf("Opera/6")!=-1);
var agt=navigator.userAgent.toLowerCase();
var mac = (agt.indexOf("mac")!=-1);
var ie = (agt.indexOf("msie") != -1);
var mac_ie = mac && ie;

var imageWin = null;

function getRealLeft(el) {
    xPos = el.offsetLeft;
    tempEl = el.offsetParent;
    while (tempEl != null) {
        xPos += tempEl.offsetLeft;
        tempEl = tempEl.offsetParent;
    }
    return xPos;
}

function getRealTop(el) {
    yPos = el.offsetTop;
    tempEl = el.offsetParent;
    while(tempEl != null){
        yPos += tempEl.offsetTop;
        tempEl = tempEl.offsetParent;
    }
    return yPos;
}

function showHideMenuNode(node_id, image_id){
	n = document.getElementById(node_id);
	i = document.getElementById(image_id);
	if(n){
		n.style.display = n.style.display == "none" ? "block" : "none";
		if(i){
			i.src = n.style.display == "none" ? skin_images + "/menu_tree_plus.gif" : skin_images + "/menu_tree_minus.gif";
		}
	}
}


function getElementHeight(Elem) {
	if(ns4){
		var elem = document.getElementById(Elem);
		return elem.clip.height;
	} else {
		if(document.getElementById) {
			var elem = document.getElementById(Elem);
		} else if (document.all){
			var elem = document.all[Elem];
		}
		if (op5) {
			xPos = elem.style.pixelHeight;
		} else {
			xPos = elem.offsetHeight;
		}
		return xPos;
	}
}

function getElementWidth(Elem) {
	if (ns4) {
		var elem = document.getElementById(Elem);
		return elem.clip.width;
	} else {
		if(document.getElementById) {
			var elem = document.getElementById(Elem);
		} else if (document.all){
			var elem = document.all[Elem];
		}
		if (op5) {
			xPos = elem.style.pixelWidth;
		} else {
			xPos = elem.offsetWidth;
		}
		return xPos;
	}
}


if(document.layers){
	_browser = "nn";
}
if(document.all){
	_browser = "ie";
}
if(navigator.userAgent.toLowerCase().match("gecko")){
	_browser= "gecko";
}
function isEmail(entry){
	var rex= /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,5})(\]?)$/;
	return rex.test(entry);
}

function delay(gap){ /* gap is in millisecs */
	var then, now;
	then = new Date().getTime();
	now = then;
	while((now-then) < gap){
		now=new Date().getTime();
	}
}

function showProductImage(image_url, image_width, image_height){
	image_width = image_width == "" ? 400 : image_width;
	image_height = image_height == "" ? 380 : image_height;

	var w = screen.width;
	var h = screen.height;
	var ww = image_width * 1 + 20;
	var wh = image_height * 1 + 35;
	var wx = (w - ww)/2;
	var wy = (h - wh)/2;

	if(imageWin != null){
		imageWin.close();
	}
	imageWin = null;
	imageWin = window.open(
		"",
		"ProductImageWindow",
		"titlebar=yes, toolbar=no, menubar=no, status=no, directories=no, resizable=yes, scrollbars=yes, top=" + wy.toString() + ", left=" + wx.toString() + ", width=" + ww.toString() + ", height=" + wh.toString() + ""
	);
	while(imageWin==null);
	imageWin.focus();

	imageWin.document.body.innerHTML = "";
	imageWin.document.write('<body style="padding:10px;margin:0px">');
	imageWin.document.write('<div align="center"><img hspace="0" vspace="0" src="' + image_url + '"></div><br/>');
	imageWin.document.write('<div align="center" style="font-family:arial;font-color:black;font-size:11px;"><a href="javascript:window.close();" style="color:#0000AA;">Close Window</a></div>');
	imageWin.document.write('</body>');
	imageWin.width = ww;
	imageWin.height = wh;
}

function showPrinterPage(url){
	var prWin = null;
	prWin = window.open(
		url,
		"PrintVer",
		"titlebar=yes, toolbar=no, menubar=yes, status=yes, directories=no, resizable=yes, scrollbars=yes, top=20, left=20, width=810, height=600"
	);
	while(prWin==null);
	prWin.focus();
}

function OnButton(bt){
	document.images[bt].src = skin_images + bt + "_on.gif";

}
function OffButton(bt){
	document.images[bt].src = skin_images + bt + "_off.gif";
}

function OnMenu(cid){
	document.images["menul_" + cid].src = skin_images + "catl_bg_on.gif";
	document.all["menur_" + cid].background = skin_images + "catr_bg_on.gif";
}
function OffMenu(cid){
	document.images["menul_" + cid].src = skin_images + "catl_bg_off.gif";
	document.all["menur_" + cid].background = skin_images + "catr_bg_off.gif";
}
var RecentTimeOut, CartTimeOut;

function ShowCart(){
	window.clearTimeout(CartTimeOut);
	if(_browser == "ie"){
		cartDiv.style.visibility =
			cartDiv.style.visibility == "hidden"?"visible":"hidden";
			document.images["cartImage"].src =
				cartDiv.style.visibility == "hidden"?
				(skin_images + "ic_expand.gif"):
				(skin_images + "ic_collapse.gif");
	}
	else if(_browser == "gecko"){
		document.getElementById('cartDiv').style.visibility =
			document.getElementById('cartDiv').style.visibility == "hidden"?"visible":"hidden";
		document.images["cartImage"].src =
			document.getElementById('cartDiv').style.visibility == "hidden"?
			(skin_images + "ic_expand.gif"):
			(skin_images + "ic_collapse.gif");
	}
	else{
		document.cartDiv.visibility = document.cartDiv.visibility  == "hidden"?"visible":"hidden";
	}
}


function ShowRecent(){
	window.clearTimeout(RecentTimeOut);
	if(_browser == "ie"){
		recentDiv.style.visibility =
			recentDiv.style.visibility == "hidden"?"visible":"hidden";
		document.images["recentImage"].src =
			recentDiv.style.visibility == "hidden"?
			(skin_images + "ic_expand.gif"):
			(skin_images + "ic_collapse.gif");
	}
	else if(_browser == "gecko"){
		document.getElementById('recentDiv').style.visibility =
			document.getElementById('recentDiv').style.visibility == "hidden"?"visible":"hidden";
		document.images["recentImage"].src =
			document.getElementById('recentDiv').style.visibility == "hidden"?
			(skin_images + "ic_expand.gif"):
			(skin_images + "ic_collapse.gif");
	}
	else{
		document.recentDiv.visibility = document.recentDiv.visibility  == "hidden"?"visible":"hidden";
	}
}

function PopUpCart(){
	CartTimeOut = window.setTimeout('ShowCart();', 1000);
}

function PopUpRecent(){
	RecentTimeOut = window.setTimeout('ShowRecent();', 1000);
}

function OnMenu(img){
	document.images[img].src = skin_images + "menu_arrow_on.gif";
}
function OffMenu(img){
	document.images[img].src = skin_images + "menu_arrow.gif";
}

function ShowPopup(src){
	var bWin = null;
	bWin = window.open(
		src,
		"PopupWind",
		"titlebar=no, toolbar=no, menubar=no, status=no, directories=no, resizable=no, scrollbars=no, top=20, left=20, width=320, height=240"
	);
	while(bWin==null);
	bWin.focus();
}

function PopUpImage(image_source, image_width, image_height){
	var bWin = null;
	bWin = window.open(
		image_source,
		"ImageWind",
		"titlebar=no, toolbar=no, menubar=no, status=no, directories=no, resizable=no, scrollbars=no, top=20, left=20, width=" + (image_width + 20) + ", height=" + (image_height + 20)
	);
	while(bWin==null);
	bWin.focus();
}

function ConfirmLogout(){
	if(orderItemsCount > 0){
		if(confirm("You have items in your cart. Logging out will empty your cart\nAre you sure want to continue?")){
			document.location = urlLogout;
		}
	}
	else{
		if(confirm("Do you really want to logout?")){
			document.location = urlLogout;
		}
	}
}

function CartConfirmEmpty(){
	if(confirm(msg_confirm_empty_cart)){
		document.location = CartEmptyUrl;
	}
}

function openWindow(winX, winY, pic, newPageTitle) {
			picWindow = window.open('','picWin','width='+winX+',height='+winY+',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no')

	picWindow.focus() // Puts focus onto new window

	if (window.picWindow) {
		// write this code into it
		var pictureCode = "<html><head><title>"+newPageTitle+"</title></head>\n"
		pictureCode += "<body style=\"border: 0; margin: 0; padding: 0; padding-bottom: 0; padding-left: 0; padding-right: 0; padding-top: 0; margin-bottom: 0; margin-left: 0; margin-right: 0; margin-top: 0; background-color: #ffffff;\" leftmargin=\"0\" topmargin=\"0\" marginheight=\"0\" marginwidth=\"0\" onblur = \"window.close()\">\n"
		pictureCode += "<div>\n"
		pictureCode += "<img src=\""+pic+"\" width=\""+winX+"\"height=\""+winY+"\" alt=\""+newPageTitle+"\">\n"
		pictureCode += "</div>\n"
		pictureCode += "</body>\n"
		pictureCode += "</html>"
		picWindow.document.open ()
		picWindow.document.write (pictureCode)
		picWindow.document.close ()
		}
	}

function closePopup()
{
	var old = $('popup');
	if (old) old.parentNode.removeChild(old);
}
function closePopupBig()
{
	var old = $('popup_big');
	if (old) old.parentNode.removeChild(old);
}
function showPopuped(title, content, parent, left, top)
{
	//remove previous
	closePopup()


	var code = '';
	code +=	'<div class="popup" id="popup">';
code +=	'	<div id="title">';
code +=	'		<a href="javascript:void(0)" onclick="closePopup(); return false"><img src="/store/img/b_close.gif" width="21" height="21" alt="close window" title="close window" align="right"></a>';
code +=	'	<span id="title116">E-mail to a Friend</span>';
code +=	'</div>';
code +=	'<div id="body116">';
code +=	'	</div>';
code +=	'</div>';


	var tmp = document.createElement('div');
	tmp.innerHTML = code;

	document.getElementsByTagName('body')[0].appendChild(tmp.firstChild);

	$('title116').innerHTML = title;
	$('body116').innerHTML = content;
	$('popup').style.left = '50%';
	$('popup').style.top = top-250+'px';
	$('popup').style.display = 'block';
	$('popup').style.marginLeft = '-200px';



	//move
	var popup = $('popup');
	//if (popup.offsetLeft + popup.pffsetWidth > parent.offsetWidth)
	//	popup.style.left = parent.offsetWidth-popup.pffsetWidth+'px';*/


}

/**
 * Retrieve the absolute coordinates of an element.
 *
 * @param element
 *   A DOM element.
 * @return
 *   A hash containing keys 'x' and 'y'.
 */
function getAbsolutePosition(element) {
  var r = { x: element.offsetLeft, y: element.offsetTop };
  if (element.offsetParent) {
    var tmp = getAbsolutePosition(element.offsetParent);
    r.x += tmp.x;
    r.y += tmp.y;
  }
  return r;
};

/**
 * Retrieve the coordinates of the given event relative to the center
 * of the widget.
 *
 * @param event
 *   A mouse-related DOM event.
 * @param reference
 *   A DOM element whose position we want to transform the mouse coordinates to.
 * @return
 *    A hash containing keys 'x' and 'y'.
 */
function getRelativeCoordinates(event, reference) {
  var x, y;
  event = event || window.event;
  var el = event.target || event.srcElement;

  if (!window.opera && typeof event.offsetX != 'undefined') {
    // Use offset coordinates and find common offsetParent
    var pos = { x: event.offsetX, y: event.offsetY };

    // Send the coordinates upwards through the offsetParent chain.
    var e = el;
    while (e) {
      e.mouseX = pos.x;
      e.mouseY = pos.y;
      pos.x += e.offsetLeft;
      pos.y += e.offsetTop;
      e = e.offsetParent;
    }

    // Look for the coordinates starting from the reference element.
    var e = reference;
    var offset = { x: 0, y: 0 }
    while (e) {
      if (typeof e.mouseX != 'undefined') {
        x = e.mouseX - offset.x;
        y = e.mouseY - offset.y;
        break;
      }
      offset.x += e.offsetLeft;
      offset.y += e.offsetTop;
      e = e.offsetParent;
    }

    // Reset stored coordinates
    e = el;
    while (e) {
      e.mouseX = undefined;
      e.mouseY = undefined;
      e = e.offsetParent;
    }
  }
  else {
    // Use absolute coordinates
    var pos = getAbsolutePosition(reference);
    x = event.pageX  - pos.x;
    y = event.pageY - pos.y;
  }
  // Subtract distance to middle
  return { x: x, y: y };
}

var EmailEvent = function (event, id) {
    var e = event || window.event;
    var pos = getRelativeCoordinates(event, document.getElementById('mainContainer'));
    var content = ''
  +'	<form name="frmEmail2Friend" action="http://www.ksmaui.com/store/index.php?p=email2friend&pid=' + id +'" method="post" onsubmit="return CheckEmail2FriendForm(this);" id="Email2Friend">'
  +'<table cellpadding="5" cellspacing="0" border="0">'
  +'		<input type="hidden" name="action" value="send"/>'
  +'	<tr>'
  +'		<td colspan="4" align="center" height="20">'
  +'			<b></b>'
  +'		</td>'
  +'	</tr>'
  +'	<tr>'
  +'		<td colspan="4" align="center" height="40">'
  +''
  +'			Please complete this form.<br />'
  +'			All fields are required.'
  +'		</td>'
  +'	</tr>'
  +'	<tr>'
  +'		<td style="width:20px;">&nbsp;</td>'
  +'		<td style="width:130px;">'
  +'			<strong>Your name:</strong><br />'
  +''
  +'			<input maxlength="64" type="text" style="width:130px;" name="yname"/>'
  +'		</td>'
  +'		<td style="width:20px;">&nbsp;</td>'
  +'		<td style="width:150px;">'
  +'			<strong>Your email address:</strong><br />'
  +'			<input maxlength="64" type="text" style="width:130px;" name="yemail"/>'
  +'		</td>'
  +'	</tr>'
  +''
  +'	<tr>'
  +'		<td>&nbsp;</td>'
  +'		<td>'
  +'			<strong>Your friend\'s name:</strong><br />'
  +'			<input maxlength="64" type="text" style="width:130px;" name="fname"/>'
  +'		</td>'
  +'		<td>&nbsp;</td>'
  +'		<td>'
  +''
  +'			<strong>Your friend\'s email:</strong><br />'
  +'			<input maxlength="64" type="text" style="width:130px;" name="femail"/>'
  +'		</td>'
  +'	</tr>'
  +'	<tr>'
  +'		<td colspan="4" height="70" align="center">'
  +'			<input type="submit" value="Send" style="width:90px;"/>'
  +'			<p><a href="javascript:void(0)" onclick="closePopup(); return false">Close Window</a></p>'
  +''
  +'		</td>'
  +'	</tr>'
  +'	</table>'
  +'	</form>'
  +'';

    showPopuped('E-mail to a Friend', content, 'body', pos.x, pos.y)
}


function SlideShowEvent(event, data){
    var e = event || window.event;
    var pos = getRelativeCoordinates(event, document.getElementById('mainContainer'));
//    var content = '<iframe width="600" height="450" frameborder="0" marginwidth="0" marginheight="0" src="http://www.ksmaui.com/store/img/preview/?pid='+id+'"></iframe>'
    showBigPopuped(data, 'body', pos.x, pos.y)
}

	var images = new Array;
	var thumbs = new Array;

function showBigPopuped(data, parent, left, top)
{
	//remove previous
	closePopupBig()

	var data = data.split("|");
	var id = data[0];
	var title = data[1];


	var code = '';
	code +=	'<div class="popup_big" id="popup_big">';
code +=	'	<div id="title">';
code +=	'		<a href="javascript:void(0)" onclick="closePopupBig(); return false"><img src="/store/img/b_close.gif" width="21" height="21" alt="close window" title="close window" align="right"></a>';
code +=	'	<span id="title116">E-mail to a Friend</span>';
code +=	'</div>';
code +=	'<div id="body116">';
code +=	'</div>';
code += '<div style="text-align:center; margin:10px"><a href="javascript:void(0)" onclick="closePopupBig(); return false">Close</a></div>';
code +=	'	</div>';
code +=	'</div>';


	var tmp = document.createElement('div');
	tmp.innerHTML = code;

	document.getElementsByTagName('body')[0].appendChild(tmp.firstChild);

	$('title116').innerHTML = title;
	$('body116').innerHTML = content;
	$('popup_big').style.left = '50%';
	$('popup_big').style.top = top-250+'px';
	$('popup_big').style.display = 'block';
	$('popup_big').style.marginLeft = '-200px';


//XMLFlashSlideshow_v3({id:'body116',swf:'/store/img/preview/v3flashslideshow/slideshow.swf',w:'600',h:'450',redirect:'',usePreloader:'true',xml:'/store/img/preview/v3flashslideshow/slideshow.php?pid=' + id + '',preventCache:'true',disableMultipleXML:'false',initXML:'%3C?xml%20version=%221.0%22%20encoding=%22utf-8%22?%3E%3Cslideshow%20version=%223%22%3E%0A%20%20%3Cstyles%3E%0A%20%20%20%20%3CPreloader%20label=%22Loading%20%7BN%7D%2525%22%20iconColor=%22#666666%22%20iconAlpha=%2270%22%20iconWidth=%2250%22/%3E%0A%20%20%20%20%3CPreloaderLabel%20font=%22Verdana%22%20size=%2210%22%20color=%22#666666%22%20bold=%22false%22/%3E%0A%20%20%20%20%3CBackground%20backgroundColor=%22#FFFFFF%22%20backgroundAlpha=%22100%22%20bevelColor=%22#FFFFFF%22%20bevelStrength=%2270%22%20borderWidth=%220%22%20borderColor=%22#FF6600%22/%3E%0A%20%20%20%20%3CLoaderAnimation%20type=%22circle%22%20color=%22#FFFFFF%22%20alphaBackground=%2220%22%20alphaInner=%2240%22%20frameWidth=%222%22%20width=%2250%22%20height=%2250%22/%3E%0A%20%20%20%20%3CDataLoader%20useAnimation=%22true%22%20useLabel=%22true%22%20labelPlacement=%22bottom%22%20fadeOutDuration=%22400%22%20textFormat=%22loader_text%22/%3E%0A%20%20%3C/styles%3E%0A%20%20%3Clocalization%3E%0A%20%20%20%20%3Ctext%20orig=%22Loading%20Data...%22%20local=%22Loading%20Data...%22%20desc=%22The%20label%20displayed%20while%20data%20file(s)%20are%20being%20loaded%22/%3E%0A%20%20%3C/localization%3E%0A%20%20%3Cfonts%3E%0A%20%20%20%20%3Cfont%20id=%22loader_text%22%20name=%22Pixelade%22%20embed=%22true%22%20size=%2213%22%20color=%22#666666%22%20bold=%22false%22%20selectable=%22false%22%20align=%22left%22/%3E%0A%20%20%3C/fonts%3E%0A%3C/slideshow%3E'});

$('body116').innerHTML='<div id="systemWorking"><img src="/store/content/skins/flat/images/dtree/busynow.gif">Loading...</div><div id="slideshow"><img id="slide_image" /></div><div id="pager"></div>';

	var url = '/store/img/preview/v3flashslideshow/ajax.php?pid=' + id
	images = new Array;
	thumbs = new Array;

	new Ajax.Request(url, {
	  method: 'get',
	  onSuccess: function(transport) {
	  	var resp = transport.responseText;
	  	eval(resp)
	  	Element.scrollTo($("popup_big"));
	  	$("slide_image").src=images[0];
	  	$("slide_image").className=0;
  		$("slide_image").onload = function (){
  			 	Element.hide('systemWorking');
	  		}
	  	var pager = $("pager");
	  	for (cnt=0; cnt<thumbs.length; cnt++){
	  		var image = document.createElement('img');
	  		image.src = thumbs[cnt];
	  		image.width = 100;
	  		image.id = cnt;
	  		image.onclick = function(image){
	  			if (image){
	  				var id = image.target.id;
	  			} else {
	  				var id = window.event.srcElement.id;
	  			}
	  			if (id != $("slide_image").className) {
		  			 Element.show('systemWorking');
		  			 $("slide_image").src=images[id];
		  			 $("slide_image").className=id;
		  			 $("slide_image").onload = function (){
		  			 	Element.hide('systemWorking');
		  			 }
	  			}
	  		}
/*	  		image.onmouseover = function(image){
	  			 Element.show('systemWorking');
	  			 $("slide_image").src=images[image.target.id];
	  			 $("slide_image").onload = function (){
	  			 	Element.hide('systemWorking');
	  			 }
	  		}*/
	  		pager.appendChild(image);
	  	}
	  },
	  onCreate: function(){
		Element.show('systemWorking');
	  },
  	  onComplete: function() {
		Element.hide('systemWorking');
	  }

	});

	//move
	//var popup = $('popup');
	//if (popup.offsetLeft + popup.pffsetWidth > parent.offsetWidth)
	//	popup.style.left = parent.offsetWidth-popup.pffsetWidth+'px';*/


}

function 	InitEmailButtons(){
	var elems = document.getElementsByClassName("mail_button");
	for (var cnt=0; cnt < elems.length; cnt++){
		elems[cnt].onclick = EmailEvent.bindAsEventListener(null,elems[cnt].id);
	}
}
function 	InitSubmpt(){
	if ($("addtocart")){
		$("addtocart").onclick = AlertTerms.bindAsEventListener(null,$("pid").value);
		$("addtocart").href = "javascript: void(0);";
	}
}

function InitPoductSlideShow(element){
	var elems = element.getElementsByClassName("slideshow_button");
	for (var cnt=0; cnt < elems.length; cnt++){
		elems[cnt].onclick = SlideShowEvent.bindAsEventListener(null,elems[cnt].id);
	}
}

function sendMail(form) {
	var error = "";
	if (!form.email.value) {
		error += "Fill your email address<br />";
	} else if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(form.email.value))
	{

	} else {
		error += "Please, enter correct email address<br />";
	}
	if (!form.name_first.value) {
		error += "Fill your first name<br />";
	}
	if (!form.name_last.value) {
		error += "Fill your last name<br />";
	}
	if (!form.subj.value) {
		error += "Fill the subject<br />";
	}
	if (!form.message.value) {
		error += "Fill the message<br />";
	}
	if (error) {
		$("error").innerHTML = error;
		return false;
	} else {
		var parameters = "email="+form.email.value+"&name_first="+form.name_first.value+"&name_last="+form.name_last.value+"&subj="+form.subj.value+"&message="+form.message.value
		var url = "/store/send_mail.php";
		new Ajax.Request(url, {
		  method: 'post',
		  parameters: parameters,
		  onSuccess: function(transport) {
		  	var resp = transport.responseText;
		  	if (resp == "true") {
		  		form.innerHTML = "<p><b>Your message was sent!</b></p>";
		  		return false;
		  	}
		  	else {
		  		error = "Unable to send message<br />";
		  		$("error").innerHTML = error;
		  		return false;
		  	}
		  }
		});
	}
	return false;
}
