// for html entities
var ENT_QUOTES = 'ENT_QUOTES';
var ENT_NOQUOTES = 'ENT_NOQUOTES';
var on_login_reload = true;

if(typeof(isIE6) == undefined){
	var isIE6 = false;
}


// Returns the number of Elements in an item - only counts those of type 1
function getNumChildren(el){
	var c = 0;
	
	if(!el){ return c; }
	
	for(a = 0; a < el.childNodes.length; a++){
		cNode = el.childNodes[a];
		if(cNode.nodeType == 1){
			c++;
		}
	}
	return c;
}
// Returns the Elements in an item - only counts those of type 1
function getChildren(el){
	var c = [];
	if(!el){ return; }
	for(a = 0; a < el.childNodes.length; a++){
		cNode = el.childNodes[a];
		if(cNode.nodeType == 1){
			c.push(cNode);
		}
	}
	return c;
}

function getFrameDocument() {
    var oIframe = document.getElementById("myframe");
    var oDoc = oIframe.contentWindow || oIframe.contentDocument;
    if (oDoc.document) {
        oDoc = oDoc.document;
    }
    return oDoc;
}

// Aligns the ABSOLUTELY positioned element to the top of the scroll window, plus the offset
function alignToWindowTop(obj , offset){
	if(isNaN(offset + 0)){
		offset = 0;
	}
	
	
	var top =  window.pageYOffset + 0;
	if(isNaN(top)){
		top = document.documentElement.scrollTop;
	}
	// Neither work
	if(isNaN(top + 0)){ return; }
	
	obj.style.top = (top + offset) + 'px';
}




function stackFunction(func, func2) {
  if (typeof func != 'function') {
    return func2;
  } else {
     return function() {
      func(this);
      func2(this);
    }
  }
}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}




function htmlentities(string, quote_style) {
    // Convert special characters to HTML entities
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_htmlspecialchars/
    // +       version: 805.3114
    // +   original by: Mirek Slugen
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: htmlspecialchars("<a href='test'>Test</a>", 'ENT_QUOTES');
    // *     returns 1: '&lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt'
    
    string = string.toString();
    
    // Always encode
    string = string.replace(/&/g , '&amp;');
    string = string.replace(/</g , '&lt;');
    string = string.replace(/>/g , '&gt;');
    
    // Encode depending on quote_style
    if (quote_style == 'ENT_QUOTES') {
        string = string.replace(/"/g, '&quot;');
        string = string.replace(/'/g, '&#039;');
    } else if (quote_style != 'ENT_NOQUOTES') {
        // All other cases (ENT_COMPAT, default, but not ENT_NOQUOTES)
        string = string.replace(/"/g, '&quot;');
    }
    
    return string;
}

// For panes and all that shizzle
function displayDiv(div){
	var d = $(div);
	
	if(!d){ return; }
	
	d.setStyle('display' , 'block');
}

function hideDiv(div){
	var d = $(div);
	
	if(!d){ return; }
	
	d.setStyle('display' , 'none');
}

function switchDivs(toClose , toOpen){
	hideDiv(toClose);
	showDiv(toOpen);
}



var userObj = {};
userObj.receiveLoginDetails = function(e){
	if(!e){ return; }
	
	$('user_name_box').innerHTML = $('user_name_box2').innerHTML = htmlentities(e['details']['name'] , ENT_QUOTES);
}

function bookmarkPage(title , url){
	var u=location.href;
	var t=document.title;
	
	if (window.sidebar) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel(t, u,"");
	} else if( window.external ) { // IE Favorite
		window.external.AddFavorite(u, t); 
	}else{
		alert('Please manually add this page to your bookmarks\' menu');
	}
	return false;
}


function detectBrowser() {
	var agt=navigator.userAgent.toLowerCase();
	if (agt.indexOf("firefox") != -1) return 'Firefox';
	if (agt.indexOf("safari") != -1) return 'Safari';
	if (agt.indexOf("msie") != -1) return 'Internet Explorer';
	if (agt.indexOf("netscape") != -1) return 'Netscape';
	return navigator.userAgent;
}

function tryLogin(){
	var elm = $('loginButton'); 
	elm.loginResponse = function(e){
		if(!e['success']){
			if(e['type'] != 'migrate'){
				//alert('Sorry, your details were not found');
                $('loginerrormsg').innerHTML = "Sorry, your details were not found";
                $('loginerrormsg').style.display = 'block';
			} else {
				window.location='/migrate-account.html';
			}
		}else{
            $('loginerrormsg').style.display = 'none';
			if(e['type'] !== 'already_logged'){
				get_login_details();
				$('loginBoxContent').innerHTML = e['loginPane'];
				closeLoginBox();
				// Refreshes the page if required to do so
				if(on_login_reload){
					window.location.reload();
				}
			}
		}
	}
	
	RPC("customer", "customer_login_ajax", elm, "loginResponse", Array($('loginname').value , $('loginpassword').value , $('rememberMeField').checked ? 1 : 0));
}


function get_login_details(){
	RPC("customer", "get_user_details_ajax", userObj, "receiveLoginDetails", Array());
}

function closeLoginBox(){
	hideDiv('topLoginBox');
}

function openLoginBox(){
	document.getElementById('minicart').style.visibility = "hidden";
	displayDiv('topLoginBox');
}

document.addEvent('domready' , function(){
	if($('openLoginBox')){
		$('openLoginBox').onclick = function(){ openLoginBox(); return false; }
	}
	if($('closeLoginBox')){
		$('closeLoginBox').onclick = function(){closeLoginBox(); return false; }
	}
	
	if($('closeLoginBox2')){
		$('closeLoginBox2').onclick = function(){closeLoginBox(); return false; }
	}
	if($('loginButton')){
		$('loginButton').onclick = function(){ tryLogin(); return false;}	
	}
});

function changeCurrency(c, elm) {
	elm.onUpdated = function(e) { 
			url=window.location.href;	
			str=/payment-failed\.html/;
			if(check=url.match(str)){
				document.location.href="/checkout.html"; /* if swopped currency on payment-failed.html then take them to checkout*/
			}else{
				document.location.reload();	
			}
			
		}
	


	RPC("currency", "change_currency", elm, "onUpdated", Array(c));
	return false;
}

function changeLanguage(l, elm) {
	elm.onUpdated = function(e) { if(e!="") { document.location=e; } }
	RPC("language", "change_language", elm, "onUpdated", Array(l));
	return false;
}

function changeSite(elm) {
	elm.onUpdated = function(e) { if(e!="") { document.location=e; } }
	RPC("language", "change_site_in_lang", elm, "onUpdated", Array());
	return false;
} 

function notifyMe(sku,loggedIn, elm, uniqueID){
	if(loggedIn == 1){
		elm.addNotifyResponse = function(e) {
			if(e === false){	
				alert('There has been a problem dealing with your request');
			}else{
				elm.style.display='none';
				document.getElementById('spanNotifyMe_'+sku+'_'+uniqueID).style.display='block';
				if(document.getElementById('notifyMeMsg')){
					document.getElementById('notifyMeMsg').style.display='none';
				}
			}
		}
		RPC("product", "notifyMe", elm, "addNotifyResponse", Array(sku));
	}else{
		doLogin();
	}
	return false;
}

function doLogin() {
	on_login_reload = true;
	window.scrollTo(0,0);
	openLoginBox();
	//alert('Please log into your account first');
    var emsg = document.getElementById('loginerrormsg');
    emsg.innerHTML = "Please log into your account first.";
    emsg.style.display = 'block';
	return false;
}

function applyFilter(loc) {
	if(loc!="") {
		document.location = loc;
	}
}

function popSizeChart(file){
    newwindow = window.open(file,'sizechart','height=150,width=400');
	if (window.focus) {newwindow.focus()}
	return false;
}

var arVersion = navigator.appVersion.split("MSIE")
var version = parseFloat(arVersion[1])

function fixPNG(myImage) 
{
    if ((version >= 5.5) && (version < 7) && (document.body.filters)) 
    {
       var imgID = (myImage.id) ? "id='" + myImage.id + "' " : ""
	   var imgClass = (myImage.className) ? "class='" + myImage.className + "' " : ""
	   var imgTitle = (myImage.title) ? 
		             "title='" + myImage.title  + "' " : "title='" + myImage.alt + "' "
	   var imgStyle = "display:inline-block;" + myImage.style.cssText
	   var strNewHTML = "<span " + imgID + imgClass + imgTitle
                  + " style=\"" + "width:" + myImage.width 
                  + "px; height:" + myImage.height 
                  + "px;" + imgStyle + ";"
                  + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
                  + "(src=\'" + myImage.src + "\', sizingMethod='scale');\"></span>"
	   myImage.outerHTML = strNewHTML	  
    }
}

function enter_poll(poll_id, elm, type) {
	if(document.getElementById('answer1_'+type) && document.getElementById('answer1_'+type).checked==true) {
		answer = 1;
	} else if(document.getElementById('answer2_'+type) && document.getElementById('answer2_'+type).checked==true) {
		answer = 2;
	} else if(document.getElementById('answer3_'+type) && document.getElementById('answer3_'+type).checked==true) {
		answer = 3;
	} else if(document.getElementById('answer4_'+type) && document.getElementById('answer4_'+type).checked==true) {
		answer = 4;
	} else if(document.getElementById('answer5_'+type) && document.getElementById('answer5_'+type).checked==true) {
		answer = 5;
	} else if(document.getElementById('answer6_'+type) && document.getElementById('answer6_'+type).checked==true) {
		answer = 6;
	} else if(document.getElementById('answer7_'+type) && document.getElementById('answer7_'+type).checked==true) {
		answer = 7;
	} else if(document.getElementById('answer8_'+type) && document.getElementById('answer8_'+type).checked==true) {
		answer = 8;
	} else {
		alert('Please select an answer');
		return false;
	}
	elm.onUpdated = function(e) { 
		document.forms['frm'+type].style.display='none';
		document.getElementById('entered'+type).style.display='block';
		if(type=="Poll") {
			for(i=0;i<e.length;i++) {
				if(document.getElementById('result_'+e[i].answer+'_rounded')) {
					document.getElementById('result_'+e[i].answer+'_rounded').style.width = e[i].result_rounded + 'px';
				}
				if(document.getElementById('result_'+e[i].answer+'')) {
					document.getElementById('result_'+e[i].answer).innerHTML = e[i].result;
				}
			}
		}
	};
	RPC("Poll", "enter_poll", elm, "onUpdated", Array(poll_id, answer, type));
	return false;
}
