
// Storage place for generic javascript functions
var SA_body = document.documentElement ? document.documentElement : (document.body ? document.body : null);

function addEvent(elm, evType, fn, useCapture) {
    var r = true;
    if(elm.addEventListener) elm.addEventListener(evType, fn, useCapture);
    else if(elm.attachEvent) r = elm.attachEvent('on' + evType, fn);
    else elm['on' + evType] = fn;
    return r;
}

function removeEvent(elm, evType, fn, useCapture) {
    if(elm.removeEventListener) elm.removeEventListener(evType, fn, useCapture);
    if(elm.detachEvent) elm.detachEvent('on' + evType, fn);
    elm['on' + evType] = null;
    return true;
}


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

function copyObj(obj) {
    var c = new Object();
    for(var e in obj) c[e] = obj[e];
    return c;
}

function mousePos(e) {
    if(!e) return null;
    var pos = new Object();

    pos['x'] = (e.pageX ? e.pageX : e.clientX + SA_body.scrollLeft);
    pos['y'] = (e.pageY ? e.pageY : e.clientY + SA_body.scrollTop);

    return pos;
}


// isInArray -- true if 'needle' is in 'haystack'
function SA_isInArray( needle, haystack ) {
    if(needle == undefined || haystack == undefined) return false;

    for(var i_hay = 0; i_hay < haystack.length; i_hay++) {
        if(needle == haystack[i_hay]) { return true; }
    }
    return false;
}

var _SA_focus_id;
function SA_setFocus(id) {
    _SA_focus_id = id;
}

var _SA_focus_ignore = new Array();
function SA_ignoreForm(form) {
    _SA_focus_ignore.push(form);
}

function SA_focusElement(el) {
    var exclusionList = new Array('hidden', 'checkbox', 'radio', 'file', 'select-one', 'select-multiple', 'reset', 'button', 'submit');
    if(el && el.type && !SA_isInArray(el.type, exclusionList) && el.style && el.style.display != 'none') {
        if(SA_elementHeight(el) + el.offsetHeight < SA_windowHeight()) { el.focus(); }
        return true;
    }
    return false;
}

// focusFirst
//  -- focuses the first 'usable' field on a page
function SA_focusFirst() {
    if(_SA_focus_id) {
        if(SA_focusElement(document.getElementById(_SA_focus_id))) { return; }
    }

    // others = 'text'
    for(var i = 0; i < document.forms.length; i++) {
        if(document.forms[i] && document.forms[i].elements &&
           !SA_isInArray(document.forms[i], _SA_focus_ignore)) {
        for(var j = 0; j < document.forms[i].elements.length; j++) {
            var element = document.forms[i].elements[j];
            if(SA_focusElement(element)) { return; }
        }
        }
    }
}

function SA_windowHeight() {
    if(window.innerHeight && typeof(window.innerHeight) == 'number') return window.innerHeight;
    else if(document.documentElement && document.documentElement.clientHeight) return document.documentElement.clientHeight;
    else if(document.body && document.body.clientHeight) return document.body.clientHeight;
    else return false;
}
function SA_elementHeight( element ) {
    // calculate the location of the element in the page by moving up the heirachy
    var yPos = element.offsetTop;
    var tempEl = element.offsetParent;
    while (tempEl != null) {
        yPos += tempEl.offsetTop;
        tempEl = tempEl.offsetParent;
    }
    return yPos;
}

function SA_scrollToElement( element ) {
    if(!element) return;

    // scroll the window to that location
    window.scrollTo(0, SA_elementHeight(element));
}

function SA_scrollToElementByName( name ) {
    element = document.getElementsByName( name )[0];

    SA_scrollToElement( element );
}

function SA_scrollToElementById( id ) {
    element = document.getElementById( id );

    SA_scrollToElement( element );
}

function SA_setErrorTag( id, text, className ) {
    var element = document.getElementById(id);

    if(element) {
        var error_tag = document.createElement('P');
        error_tag.className = className;
        error_tag.appendChild(document.createTextNode(text));
        element.parentNode.replaceChild(error_tag, element);
    }
}

// timezone function, returns the current timezone
function SA_getTimezone() {
    var tz = "Etc/GMT";
    var d = new Date();
    var gmtHours = Math.round(d.getTimezoneOffset()/60);

    // posix times are backwards
    if (gmtHours > 0) tz += "+";
    if (gmtHours != 0) tz += gmtHours;

    return tz;
}

function SA_updateTimezoneField(el) {
    var tz = SA_getTimezone();
    if(el && el.type && el.type == 'hidden') { el.value = tz; }
    else if(el && el.type && el.type == 'select-one') {
        for (i = 0; i <= el.options.length; i++)
            if (el.options[i].value == tz) { el.options[i].selected = true; break; }
    }
}

// SA_status -- returns the status of the SA_functions. makes it possible to check if it was loaded or not
function SA_status() {
    return "SwapAce.com Javascript Library";
}

var SA = window.SA || {};

SA.Utility = {
status : function() { return "SwapAce.com Javascript Library"; },

GetXmlHttpObject : function() {
    var objXMLHttp = null

    if (window.XMLHttpRequest) {
        objXMLHttp = new XMLHttpRequest()
    } else if (window.ActiveXObject) {
        objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP")
    }

    return objXMLHttp
},

addEvent : function(elm, evType, fn, useCapture) {
    if(elm.addEventListener) {
        elm.addEventListener(evType, fn, useCapture);
        return true;
    }
    else if(elm.attachEvent) {
        var r = elm.attachEvent('on' + evType, fn);
        return r;
    }
    else {
        elm['on' + evType] = fn;
    }
    return true;
},

removeEvent : function(elm, evType, fn, useCapture) {
    if(elm.removeEventListener) {
        elm.removeEventListener(evType, fn, useCapture);
    }
    if(elm.detachEvent) {
        elm.detachEvent('on' + evType, fn);
    }
    elm['on' + evType] = null;

    return true;
},


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

hideElement : function(el) {
    el.style.display = 'none';
},

showElement : function(el) {
    el.style.display = '';
},

isElementHidden : function(el) {
    return el.style.display == 'none';
},

removeAllChildren : function(el) {
    while (el.firstChild) {
        el.removeChild(el.firstChild);
    }
},

getLeft : function(element) {
    if (element.getBoundingClientRect) { // IE
        box = element.getBoundingClientRect();
        return box.left - 2;
    }

    var curNode = element;
    var left = 0;

    while (curNode != null) {
        left += curNode.offsetLeft;
        curNode = curNode.offsetParent;
    }

    return left;
},

getTop : function(element) {
    if (element.getBoundingClientRect) { // IE
        box = element.getBoundingClientRect();
        return box.top - 2;
    }

    var curNode = element;
    var top = 0;

    while (curNode != null) {
        top += curNode.offsetTop;
        curNode = curNode.offsetParent;

    }

    return top;
}
};

// Browser Detection
var SA_BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
SA_BrowserDetect.init();

// DD hack for IE function
function SA_DDIE(divID) {
    if(SA_BrowserDetect.browser == 'Explorer') {
        var divEl = document.getElementById(divID);
        var selectEl = divEl.getElementsByTagName('SELECT');

        for(i=0; i<selectEl.length; i++) {
            var width = selectEl[i].style.width;
            if(SA_BrowserDetect.version >= 7) {
                selectEl[i].onmousedown = function(event){this.style.width=''; divEl.style.borderRight = '1px solid gray';};
            }
            else {
                selectEl[i].onmouseover = function(event){
                    this.style.width='';
                    divEl.style.borderRight = '1px solid gray';
                    this.onmouseout = function(event){this.style.width=width; divEl.style.borderRight = '';};
                };
                selectEl[i].onmousedown = function(event){this.onmouseout = function(event){};}
            }
            selectEl[i].onchange = function(event){this.style.width=width; divEl.style.borderRight = '';};
            selectEl[i].onblur = function(event){this.style.width=width; divEl.style.borderRight = '';};
        }
    }
}

// Please wait ... implementation
function SA_PW_windowHeight() {
    if(window.innerHeight && typeof(window.innerHeight) == 'number') return window.innerHeight;
    else if(document.documentElement && document.documentElement.clientHeight) return document.documentElement.clientHeight;
    else if(document.body && document.body.clientHeight) return document.body.clientHeight;
    else return false;
}
function SA_PW_elementHeight( element ) {
    // calculate the location of the element in the page by moving up the heirachy
    yPos = element.offsetTop;
    tempEl = element.offsetParent;
    while (tempEl != null) {
        yPos += tempEl.offsetTop;
        tempEl = tempEl.offsetParent;
    }
    return yPos;
}

function SA_PW_pageWidth()
{
    return window.innerWidth != null? window.innerWidth: document.documentElement && document.documentElement.clientWidth ? document.documentElement.clientWidth:document.body != null? document.body.clientWidth:null;
}

function SA_PW_pageHeight()
{
    return window.innerHeight != null? window.innerHeight: document.documentElement && document.documentElement.clientHeight ? document.documentElement.clientHeight:document.body != null? document.body.clientHeight:null;
}

function SA_PW_posLeft()
{
    return typeof window.pageXOffset != 'undefined' ? window.pageXOffset:document.documentElement && document.documentElement.scrollLeft? document.documentElement.scrollLeft:document.body.scrollLeft? document.body.scrollLeft:0;
}

function SA_PW_posTop()
{
    return typeof window.pageYOffset != 'undefined' ? window.pageYOffset:document.documentElement && document.documentElement.scrollTop? document.documentElement.scrollTop: document.body.scrollTop?document.body.scrollTop:0;
}

function SA_PW_$(x)
{
    return document.getElementById(x);
}

function SA_PW_scrollFix()
{
    var obol=SA_PW_$('ol');
    obol.style.top=SA_PW_posTop()+'px';
    obol.style.left=SA_PW_posLeft()+'px';
}

function SA_PW_sizeFix()
{
    var obol=SA_PW_$('ol');
    obol.style.height=SA_PW_pageHeight()+'px';
    obol.style.width=SA_PW_pageWidth()+'px';
}

function SA_PW_kp(e)
{
    ky=e?e.which:event.keyCode;
    if(ky==88||ky==120)SA_PW_hm();
    return false
}

function SA_PW_inf(h)
{
    tag=document.getElementsByTagName('select');
        for(i=tag.length-1;i>=0;i--)tag[i].style.visibility=h;

    tag=document.getElementsByTagName('iframe');
        for(i=tag.length-1;i>=0;i--)tag[i].style.visibility=h;

    tag=document.getElementsByTagName('object');
        for(i=tag.length-1;i>=0;i--)tag[i].style.visibility=h;
}

function SA_PW_dis(d)
{
    form = document.getElementsByTagName('form');

    // Input fields
    for(i=form.length-1; i>=0; i--) {
        inputs = form[i].getElementsByTagName('input');
        for(j=inputs.length-1;j>=0;j--) {
            tempId = inputs[j].id;
            tempName = inputs[j].name;
            tempVal = inputs[j].value;
            inputs[j].disabled = d;

            var hiddenEl = document.createElement('input');
            hiddenEl.setAttribute('type', 'hidden');
            hiddenEl.setAttribute('id', tempId);
            hiddenEl.setAttribute('name', tempName);
            hiddenEl.setAttribute('value', tempVal);
            form[i].appendChild(hiddenEl);
        }
    }

    // Select fields
    for(i=form.length-1; i>=0; i--) {
        selects = form[i].getElementsByTagName('select');
        for(j=selects.length-1;j>=0;j--) {
            tempId = selects[j].id;
            tempName = selects[j].name;
            tempVal = selects[j].value;
            selects[j].disabled = d;

            var hiddenEl = document.createElement('input');
            hiddenEl.setAttribute('type', 'hidden');
            hiddenEl.setAttribute('id', tempId);
            hiddenEl.setAttribute('name', tempName);
            hiddenEl.setAttribute('value', tempVal);
            form[i].appendChild(hiddenEl);
        }
    }

    //tag=document.getElementsByTagName('select');
        //for(i=tag.length-1;i>=0;i--)tag[i].disabled=d;

    //tag=document.getElementsByTagName('input');
        //for(i=tag.length-1;i>=0;i--)tag[i].disabled=d;
}

function SA_PW_popup_wait()
{
    var obl='dialogBox';
    var wd='400';
    var ht='200';

    var v='visible';
    var h='hidden';
    var b='block';
    var p='px';
    var obol=SA_PW_$('ol'); var obbxd = SA_PW_$('mbd');
    if(SA_PW_$(obl)) {
        obbxd.innerHTML = SA_PW_$(obl).innerHTML;
        obol.style.height=SA_PW_pageHeight()+p;
        obol.style.width=SA_PW_pageWidth()+p;
        obol.style.top=SA_PW_posTop()+p;
        obol.style.left=SA_PW_posLeft()+p;
        obol.style.display=b;
        var tp=SA_PW_posTop()+((SA_PW_pageHeight()-ht)/2)-12;
        var lt=SA_PW_posLeft()+((SA_PW_pageWidth()-wd)/2)-12;
        var obbx=SA_PW_$('mbox');
        obbx.style.top=(tp<0?0:tp)+p;
        obbx.style.left=(lt<0?0:lt)+p;
        obbx.style.width=wd+p;
        obbx.style.height=ht+p;
        SA_PW_inf(v);
        //SA_PW_dis(true); //** not working because the data won't get posted to the server and cause the form to stuck **
        obbx.style.display=b;
    }
    return false;
}

function SA_PW_hm()
{
    var v='visible';
    var n='none';
    if(SA_PW_$('ol')) SA_PW_$('ol').style.display=n;
    if(SA_PW_$('mbox')) SA_PW_$('mbox').style.display=n;
    SA_PW_inf(v);
    document.onkeypress=''
}

function SA_PW_initmb()
{
    var ab='absolute';
    var n='none';
    var obody=document.getElementsByTagName('body')[0];
    var frag=document.createDocumentFragment();
    var obol=document.createElement('div');
    obol.setAttribute('id','ol');
    obol.style.display=n;
    obol.style.position=ab;
    obol.style.top=0;
    obol.style.left=0;
    obol.style.zIndex=998;
    obol.style.width='100%';
    frag.appendChild(obol);
    var obbx=document.createElement('div');
    obbx.setAttribute('id','mbox');
    obbx.style.display=n;
    obbx.style.position=ab;
    obbx.style.zIndex=999;
    var obl=document.createElement('span');
    obbx.appendChild(obl);
    var obbxd=document.createElement('div');
    obbxd.setAttribute('id','mbd');
    obl.appendChild(obbxd);
    frag.insertBefore(obbx,obol.nextSibling);
    obody.insertBefore(frag,obody.firstChild);
    window.onscroll = SA_PW_scrollFix; window.onresize = SA_PW_sizeFix;
}
