/* iloop stands for inner loop counter. */
var loop, iloop;

var w3cDOM = (typeof document.getElementById != "undefined" && typeof document.createElement != "undefined") ? true : false;

try {
  document.execCommand('BackgroundImageCache', false, true);
} catch(e) {}

document.getUniqueId = function () {
    var prefix = "random";
    var suffix;
    do {
        suffix = Math.round (Math.random () * 1000000000000000000);
    } while (typeof document.getElementById (prefix + suffix) == "undefined" && document.getElementById (prefix + suffix) == null);
    return prefix + suffix;
}


// Function initJS is executed at the end of page (/layout/default.vm), before external files load.
// Fake window.onLoad. 
var initJS = function() {};
function listenEvent (target, type, listener) {
    if( target==window && type=='load' ) {
    	var tmp = initJS;
    	initJS = function() {tmp(); listener();};
    } else if (typeof target.addEventListener != "undefined") {
        target.addEventListener (type, listener, false);
    } else if (typeof target.attachEvent != "undefined") {
        target.attachEvent ("on" + type, listener);
    }
}

function unlistenEvent (target, type, listener) {
    if (typeof target.removeEventListener != "undefined") {
        target.removeEventListener (type, listener, false);
    } else if (typeof target.detachEvent != "undefined") {
        target.detachEvent ("on" + type, listener);
    }
}


function makeLabelsMoveFocus () {//functionality for Safari
	function moveFocus (source) {
		if (source.getAttribute) {
		var id = source.getAttribute ("for");
			if (typeof document.getElementById (id) != "undefined" && document.getElementById (id) != null) {
				source = document.getElementById (id);
				if ((source.nodeName.toLowerCase () == "input" && (source.type == "checkbox" || source.type == "radio" || source.type == "text" || source.type == "password")) || source.nodeName.toLowerCase () == "select") {
					if (source.type == "radio") {
						source.checked = true;
					} else if (source.type == "checkbox") {
						source.checked = !source.checked ? true : false;
					}
					source.focus ();
				}
			}
		}
	}
	var labels = document.getElementsByTagName ("label");
	for (loop = 0; loop < labels.length; loop ++) {
		listenEvent (labels.item (loop), "click", function () {moveFocus (this);});
	}
}
if (w3cDOM && navigator.userAgent.indexOf ("Safari") != -1) {
	listenEvent (window, "load", makeLabelsMoveFocus);
}

/* encodeToURI
** encodes text to URI standard
** based on http://www.worldtimzone.com/res/encode/
*/
function utf8(wide) {
	var c, s;
	var enc = '';
	var i = 0;
	while( i<wide.length ) {
		c= wide.charCodeAt(i++);
		// handle UTF-16 surrogates
		if( c>=0xDC00 && c<0xE000 ) { continue;
		}
		if( c>=0xD800 && c<0xDC00 ) {
			if( i>=wide.length ) { continue;
			}
			s = wide.charCodeAt(i++);
			if( s<0xDC00 || c>=0xDE00 ) { continue;
			}
			c = ((c-0xD800)<<10)+(s-0xDC00)+0x10000;
		}
		// output value
		if( c<0x80 ) { enc += String.fromCharCode(c);
		} else if( c<0x800 ) { enc += String.fromCharCode(0xC0+(c>>6),0x80+(c&0x3F));
		} else if( c<0x10000 ) { enc += String.fromCharCode(0xE0+(c>>12),0x80+(c>>6&0x3F),0x80+(c&0x3F));
		} else { enc += String.fromCharCode(0xF0+(c>>18),0x80+(c>>12&0x3F),0x80+(c>>6&0x3F),0x80+(c&0x3F));
		}
	}
	return enc;
}

var hexchars = "0123456789ABCDEF";

function toHex(n) {
	return hexchars.charAt(n>>4)+hexchars.charAt(n & 0xF);
}

var okURIchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-";

function encodeURIComponentNew(s) {
	var s = utf8(s);
	var c;
	var enc = '';
	for (var i= 0; i<s.length; i++) {
		if (okURIchars.indexOf(s.charAt(i))==-1) {
			enc += '%'+toHex(s.charCodeAt(i));
		} else {
			enc += s.charAt(i);
		}
	}
	return enc;
}
function encodeToURI(text) {
	if( text=='' ) { 
		return text;
	}
	var encodedText = '';
	if( typeof encodeURIComponent!='undefined' && encodeURIComponent!=null ) {
		encodedText = encodeURIComponent(text);
	} else if( typeof encodeURI!='undefined' && encodeURI!=null ) {
		encodedText = encodeURI(text);
	} else {
		// Need to mimic the JavaScript version
		// Netscape 4 and IE 4 and IE 5.0
		encodedText = encodeURIComponentNew(text);
	}
	return encodedText;
}
/* encodeToURI
** END
*/


function URISetParameter (URI, name, value) {
    if (URI.indexOf (name + "=") != -1) {
        var re = new RegExp ("(" + name + ")=[^&]*", "");
        return URI.replace (re, "$1=" + value);
    } else if (URI.indexOf ("?") != -1) {
        return URI += ("&" + name + "=" + value);
    } else {
        return URI += ("?" + name + "=" + value);
    }
}


function setCookie(name, value, days) {
	function getExp( d ) {
		var exp = new Date();
		exp.setTime (exp.getTime() + d);
		return '; expires=' + exp.toGMTString();
	}
	
	if (value.length == 0) {
		document.cookie = name + "=" + getExp(-1000) + ";path=/" + ( ( typeof domainName != "undefined"  ) ? ";domain=."+domainName+";" : "" );
	} else {
		document.cookie = name + "=" + value + getExp(days*24*60*60*1000) + ";path=/" + ( ( typeof domainName != "undefined" ) ? ";domain=."+domainName+";" : "" );
	}
}
function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) {
        	return null;
        }
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}


function removeNode( node ) { //TODO Check if it exists in ie
    var parentNode = node.parentNode;
    parentNode.removeChild (node);
}


function shrinkAmpCharEntRefs (string) {
    return string.replace (/&amp;/g, "&")
}

function forAll(list, callback) {
	for(var i = 0; i < list.length; i++)
		callback.call(list[i]);
}

function findByClassName(list, className) {
	var rv = [];
	for(var i = 0; i < list.length; i++) {
		var e = list[i];
		if((typeof e.className == 'string') && hasClass(e, className))
			rv.push(e);
	}
	return rv;
}

function hasClass(node, cName) {
	var has = false;
		var classes = node.className.split(' ');
	  for(var i=0; i <classes.length; i++) {
			if(classes[i] == cName)
				has = true;
	  }
 return has;
}

function addClass(node, cName) {
	if(!hasClass(node, cName))
		node.className += ' ' + cName;
}

function removeClass(node, cName) {
	if(hasClass(node, cName)) {
		var classes = node.className.split(' ');
	  for(var i=0; i <classes.length; i++)
			if(classes[i] == cName)
				classes[i] = '';
		node.className = classes.join(' ');
	}
}

function cycleClasses(node, classes) {
	for(var i=0; i < classes.length; i++) {
		if(hasClass(node, classes[i])) {
			removeClass(node, classes[i]);
			addClass(node, classes[(i+1) % classes.length]);
			return;
		}
	}
	addClass(node, classes[0]);
}

function psGroupsChanged(value) {
	if (value=='0') {
		if ($('#psGroupSelectionEq').attr('checked')) {
			$('#pseller_group_id').attr('name','s_nq_pseller_group_id');
		} else {
			$('#pseller_group_id').attr('name','s_eq_pseller_group_id');
		}
	} else {
		if ($('#psGroupSelectionEq').attr('checked')) {
			$('#pseller_group_id').attr('name','s_eq_pseller_group_id');
		} else {
			$('#pseller_group_id').attr('name','s_nq_pseller_group_id');
		}
	}
}

function psGroupSelectionChanged(value) {
	if (value=='eq') {
		if ($('#pseller_group_id').val()!='0') {
			$('#pseller_group_id').attr('name','s_eq_pseller_group_id');
		} else {
			$('#pseller_group_id').attr('name','s_nq_pseller_group_id');
		}
	} else {
		if ($('#pseller_group_id').val()!='0') {
			$('#pseller_group_id').attr('name','s_nq_pseller_group_id');
		} else {
			$('#pseller_group_id').attr('name','s_eq_pseller_group_id');
		}
	}
}	

