//Global js file

//var RootURL = '/Iconico/';		//dev
var RootURL = 'http://www.iconico.com/';						//live - but be full url for store to work

function Setup() {}	//used to be stuff in here! no it's not needed but every body tag has it so we need it

//Do the PngFix
$(document).ready(function(){
	//remove backgrounds for footers as the links get broken in IE6 by pngfix
	if ($.browser.msie && parseInt($.browser.version) < 7) {
		$('.sectionFoot, .magicTableFoot').css('background-image', 'none');
	}
	$('body').pngFix();
	
	//Service Box overlay
	$('.sbox').hover(
		function () {
			$(this).find('.sboxover').css('display','block').fadeTo('slow', 0.9);
		}, 
		function () {
			$(this).find('.sboxover').fadeOut();
		}
	);
});


function Screenshot(Img) {
	window.open(Img,'screenshot','status=no,toolbar=no,menubar=no,location=no,resizable=yes',true);
	return false;
}

function getCookieVal(offset) {
	var endstr = document.cookie.indexOf (";", offset);
	if (endstr == -1)
	endstr = document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr));
}

function getCookie(name) {
	var arg = name + "=";
	var i = 0;
	while (i < document.cookie.length) {
		var j = i + arg.length;
		if (document.cookie.substring(i, j) == arg)
			return getCookieVal (j);
		i = document.cookie.indexOf(" ", i) + 1;
		if (i == 0)
			break; 
	}
	return null;
}

function setCookie(name, value) {
	document.cookie = name + "=" + escape (value) + "; path=/";
}

function doReloader() {
	document.location.href = document.location.href;
}

//id only set in eSellerate page
function doPTNFocus(id) {
	if (id == null) { id = 'PTN'}
	var objtxt = document.getElementById(id);
	if (objtxt.value == 'your email') {
		objtxt.value = '';
	}
}

//id only set in eSellerate page
function doPTN(id) {
	if (id == null) { id = 'PTN'}
	var objtxt = document.getElementById(id);
	document.location.href = RootURL + 'connect/maillist.aspx?PTN=' + objtxt.value;
}

function doHTMLValid() {
	var objtxt = document.getElementById('HTMLValid');
	document.location.href = RootURL + 'HTMLValidator/index.aspx?HTMLValid=' + escape(objtxt.value);
}

function EmailLink(txt) { document.location.href = 'mailto:' + txt; }

function SendToFriend() {
	window.open(RootURL + 'connect/sendToFriend.aspx?FriendURL=' + escape(document.location.href), 'sendToFriend', 'width=512,height=512'); 
}

function doPrint() {
	objContent = document.getElementById('divContent');
	if (objContent) {
		objContent.style.position = 'static';
		objContent.style.padding = '120px 0px 0px 10px';
		objContent.style.width = '625px';
	}
	objHead = document.getElementById('hdrHead');
	if (objHead) {
		objHead.style.left = '120px';
	}
	objSubHead = document.getElementById('hdrSubHead');
	if (objSubHead) {
		objSubHead.style.left = '172px';
	}
	objNavBar = document.getElementById('divNavBar');
	if (objNavBar) {
		objNavBar.style.display = 'none';
	}
	objSideBar = document.getElementById('divSideBar');
	if (objSideBar) {
		objSideBar.style.display = 'none';
	}
	window.print();
}

//id only set in eSellerate page
function doPageSearch(id) {
	if (id == null) { id = 'q'}
	document.location.href = RootURL + 'connect/search.aspx?q=' + escape(document.forms[0][id].value);
}

//id only set in eSellerate page
function doPageSearchFocus(id) {
	if (id == null) { id = 'q'}
	var objtxt = document.getElementById(id);
	if (objtxt.value == 'Search...') {
		objtxt.value = '';
	}
}

// Horizontal Menu javascript
// built by http://www.iconico.com

var objTimer;
var objDrop;
var objMenuLast;

//shows menu
function appear(id) {
	var objMenu = document.getElementById(id.replace('X', ''));
	clearTimeout(objTimer);	//remove any old timers
	if (objMenu != objMenuLast)	//if we're on a new menu then hide the last immediatly
		doDisappear();
	//style
	objMenu.style.backgroundColor = '#0773DF'; //#0066CB';
	objMenuLast = objMenu;
	//dropdown
	//objDrop = objMenu.childNodes[1];	//get the menu node
	objDrop = document.getElementById(objMenu.id + 'X');
	if (objDrop) {
		objDrop.style.left = parseInt(findPosX(objMenu)) + 'px';	//get left position
		objDrop.style.display = 'inline';
	}
	checkInter("SELECT", false, objDrop);
}

//hides a menu
function disappear(id) {
	var objMenu = document.getElementById(id.replace('X', ''));
	objMenuLast = objMenu;
	//objDrop = objMenu.childNodes[1];	//get the menu node
	objDrop = document.getElementById(objMenu.id + 'X');
	objTimer = setTimeout('doDisappear();', 400);
}

//internal function for hiding menu
function doDisappear() {
	if (objMenuLast)
		objMenuLast.style.backgroundColor = '';
	if (objDrop)
		objDrop.style.display = 'none';
	checkInter("SELECT", true, objDrop);
}

//checks if nav intersects select boxes
function checkInter(strTag, blnShow, objNav) {

	var sel = document.getElementsByTagName(strTag);
	if (objNav) {
		//Create the intersection array if needed
		if (!objNav.smartIntersect) {
			var arrSel = new Array;
			var objDropR = new Recto(objNav);	//dropdown list rectangle
			for (var i=0; i<sel.length; i++) {
				var objSelR = new Recto(sel[i]);
				arrSel[i] = RectoInter(objDropR, objSelR)	//check select is under the nav
			}
			objNav.smartIntersect = arrSel;	//asign to DOM object for later access
		}

		//apply the styles to select dropdowns as needed
		for (var i=0; i<sel.length; i++) {
			if (objNav.smartIntersect[i]) {
				sel[i].style.visibility = blnShow ? "visible" : "hidden"; 
			}
		}
	}
}

//Rectangle object constructor, takes any DOM object
function Recto(obj) {
	if (obj) {
		this.left = findPosX(obj);
		this.top = findPosY(obj);
		this.width = obj.offsetWidth;
		this.height = obj.offsetHeight;
		this.bottom = this.top + this.height;
		this.right = this.left + this.width;
	}
}

//checks to see if two Recto objects intersect
function RectoInter(r1, r2) {
	var inter = false;
	//Find the leftmost etc rectangle. 
	var leftMost = r1.left < r2.left ? r1 : r2;
	var nonLeftMost = r1.left >= r2.left ? r1 : r2;
	var topMost = r1.top < r2.top ? r1 : r2;
	var nonTopMost = r1.top >= r2.top ? r1 : r2;
/*  If the left x co-ordinate of the non-leftmost rectangle is between the 
left and the right of the leftmost rectangle, you have the left cordinate of 
your intersection. If it is to the right you have no intersection, and the 
rectangles don't overlap. */
	if (nonLeftMost.left >= leftMost.left && nonLeftMost.left <= leftMost.right && nonTopMost.top >= topMost.top && nonTopMost.top <= topMost.bottom) inter = true;
	return inter;
}


//return screen X position
function findPosX(obj) {
	var curleft = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

//return screen Y position
function findPosY(obj) {
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}


//Sub Menu
function appearSub(objSubMenu) {
	objSubMenu.style.width = '195px';
}

function disappearSub(objSubMenu) {
	objSubMenu.style.width = '99px';
}







//------------------------------------------------------------------------------
// Top level error-handling
//------------------------------------------------------------------------------

// guard against recursive error popups
if (location.href.indexOf("/err0r.aspx?") == -1) {
	//window.onerror = Window_onError;	//uncomment to allow JS error reporting
}

function Window_onError(sMsg, sUrl, sLine) {
	try {
		var oParams = {
			message:sMsg, 
			uri:location.href,
			frameset:getFrames(window.top), 
			line:sLine,
			stack:stacktrace()
		};
		var sUrl = RootURL + "connect/err0r.aspx?"
		for (var sName in oParams) {
			sUrl += sName + "=" + oParams[sName] + "&";
		}
		makeAJAXRequest(sUrl);
	} catch (e) {
		//ignore
	}
	return true;
}

// This function returns a string giving the names and urls of all the frames in the top window that errored.
function getFrames(objWindow) {
	if (objWindow.frames.length == 0) {
		return "";
	} else {
		var a = [" frameset*:*" + objWindow.location.href];
		for (var i = 0; i < objWindow.frames.length; i++) {
			a[a.length] = " " + objWindow.frames[i].name + "*:*" + objWindow.frames[i].location.href;
		}
		return a.join("|");
	}
}

// This function returns the name of a given function. It does this by
// converting the function to a string, then using a regular expression
// to extract the function name from the resulting code.
function funcname(f) {
    var s = f.toString().match(/function[^\)]*\)/)[0];
    if ((s == null) || (s.length == 0)) return "anonymous";
    return s;
}

// This function returns an array that contains a "stack trace."
function stacktrace() {
    var n, o;
    var s = [];  // This is the array we'll return.
    // Loop through the stack of functions, using the caller property of
    // one arguments object to refer to the next arguments object on the
    // stack.
    if (arguments.caller) {
		for (var a = arguments.caller.caller; a != null; a = a.caller) {
			// Add the name of the current function to the return value.
			n = funcname(a.callee);
			o = getArgs(a);
			s[s.length] = n + " + " + o;

			// Because of a bug in Navigator 4.0, we need this line to break.
			// a.caller will equal a rather than null when we reach the end 
			// of the stack. The following line works around this.
			if (a.caller == a) break;
		}
    }
    return s.join("\n");
}

function getArgs(a) {
	var b = [];
	if (a != null) for (var i = 0; i < a.length; i++) b[b.length] = a[i] + " {" + typeof(a[i]) + "}";
	return b.join(", ");
}


var http_request = false;

function makeAJAXRequest(url) {
    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) {
        //alert('Giving up :( Cannot create an XMLHTTP instance');
        return false;
    }
    //http_request.onreadystatechange = alertContents;	//removed for now
    http_request.open('GET', url, true);
    http_request.send(null);
}

function alertContents() {
    if (http_request.readyState == 4) {
        if (http_request.status == 200) {
            var responseText = http_request.responseText;
			//alert(responseText);
			document.getElementById('divReturn').innerHTML = responseText;
        } else {
            alert('There was a problem with the request.');
        }
    }
}
