/*
Provides cross-browser interface for basic functions.
Browser differences are handled here.
*/

var bIE = (document.all) ? true : false;
var bOPERA = (navigator.userAgent.toLowerCase().indexOf('opera')!=-1);

//helper function to create the form
function getNewSubmitForm(doc){
 var submitForm = doc.createElement("FORM");
 doc.body.appendChild(submitForm);
 submitForm.method = "POST";
 return submitForm;
}

//helper function to add elements to the form
function createNewFormElement(doc, inputForm, elementName, elementValue){
  var newElement = doc.createElement('input');
  newElement.type = 'hidden';
  newElement.name = elementName;
  newElement.value = elementValue;
  inputForm.appendChild(newElement);
  return newElement;
}

function generatePostURLForGetAndSubmit(query_string, destinationPath, doc) {
	var doAction = query_string.split("?");
	var param_string = doAction[1];
	var final_destination = destinationPath + doAction[0]; 
	var param_array = param_string.split("&");
	var submitForm = getNewSubmitForm(doc)
	
	for (var i=0;i<param_array.length;i++) {
		param_array[i] = param_array[i].split("=");
	    createNewFormElement(doc, submitForm, param_array[i][0], unescape(param_array[i][1]));
	}
	submitForm.action= final_destination;
	submitForm.submit();
}

/*
Gets the width of the document in the specified window object.
*/
function getDocWidth(theWin) {
    if (bIE) {
        return theWin.document.body.clientWidth;
    }
    return theWin.innerWidth;
}

/*
Gets the height of the document in the specified window object.
*/
function getDocHeight(theWin) {
    if (bIE) {
        return theWin.document.body.clientHeight;
    }
    return theWin.innerHeight;
}

/*
Gets X scroll position of specified window
*/
function getScrollX(theWin) {
    if (bIE) {
        return theWin.document.body.scrollLeft;
    }
    return theWin.scrollX;
}

/*
Gets Y scroll position of specified window
*/
function getScrollY(theWin) {
    if (bIE) {
        return theWin.document.body.scrollTop;
    }
    return theWin.scrollY;
}

/*
Gets the element object with specified ID in the specified window.
*/
function getElemById( theWin, id) {
    if (!theWin) {
        return null;
    }
    return theWin.document.getElementById( id );
}

/*
Sets the left, top, width and height style properties of the element
with specified ID in the specified window.
The properties must be specified as integers (pixels).
To leave out a particular property, just pass in "" (or any non-integer String).
For example: To set left & top properties and leave out width & height :
    setElemByIdBounds( window.self, "button1", 200, 50, "", "");
*/
function setElemByIdBounds( theWin, id, posLeft, posTop, width, height ) {
    setElemBounds( getElemById(theWin, id), posLeft, posTop, width, height );
}

/*
Sets the left, top, width and height style properties of the
specified element object.
The properties must be specified as integers (pixels).
To leave out a particular property, just pass in "" (or any non-integer String).
For example: To set left & top properties and leave out width & height :
    setElemBounds( button1Ref, 200, 50, "", "");
*/
function setElemBounds( elem, posLeft, posTop, width, height ) {
    if (elem) {
        if (elem.style) {
            if (bIE || bOPERA) {
                if (!isNaN(parseInt(posTop))) {
                    elem.style.pixelTop = posTop;
                }
                if (!isNaN(parseInt(posLeft))) {
                    elem.style.pixelLeft = posLeft;
                }
                if (!isNaN(parseInt(width))) {
                    elem.style.pixelWidth = width;
                }
                if (!isNaN(parseInt(height))) {
                    elem.style.pixelHeight = height;
                }
            } else {
                if (!isNaN(parseInt(posTop))) {
                    elem.style.top = posTop+'px';
                }
                if (!isNaN(parseInt(posLeft))) {
                    elem.style.left = posLeft+'px';
                }
                if (!isNaN(parseInt(width))) {
                    elem.style.width = width+'px';
                }
                if (!isNaN(parseInt(height))) {
                    elem.style.height = height+'px';
                }
            }

        }
    }
}

/*
Sets the visibility of the element
with specified ID in the specified window.
Parameter vis must be either "visible" or "hidden".
*/
function setElemByIdVisibility( theWin, id, vis ) {
    setElemVisibility( getElemById(theWin, id), vis);
}

/*
Sets the visibility of the specified element object.
Parameter vis must be either "visible" or "hidden".
*/
function setElemVisibility( elem, vis ) {
    if (elem) {
        if (elem.style) {
            elem.style.visibility = vis;
        }
    }
}

/*
Sets the display property of the element
with specified ID in the specified window.
Parameter disp may be "none", "block", "inline", etc.
*/
function setElemByIdDisplay( theWin, id, disp ) {
    setElemDisplay( getElemById(theWin, id), disp);
}

/*
Sets the display property of the specified element object.
Parameter disp may be "none", "block", "inline", etc.
*/
function setElemDisplay( elem, disp ) {
    if (elem) {
        if (elem.style) {
            elem.style.display = disp;
        }
    }
}

/*
Gets the top coordinate (pixels) of the element
with specified ID in the specified window.
*/
function getElemByIdTop( theWin, id ) {
    return getElemTop( getElemById(theWin, id) );
}

/*
Gets the top coordinate (pixels) of the specified element object.
*/
function getElemTop( elem ) {
    if (elem) {
        if (elem.style) {
            if (bIE || bOPERA) {
                return elem.style.pixelTop;
            } else {
                var topInt = parseInt(elem.style.top);
                if (isNaN(topInt)) {
                    topInt = 0;
                }
                return topInt;
            }
        }
    }
    return 0;
}

/*
Gets the left coordinate (pixels) of the element
with specified ID in the specified window.
*/
function getElemByIdLeft( theWin, id ) {
    return getElemLeft( getElemById(theWin, id) );
}

/*
Gets the left coordinate (pixels) of the specified element object.
*/
function getElemLeft( elem ) {
    if (elem) {
        if (elem.style) {
            if (bIE|| bOPERA) {
                return elem.style.pixelLeft;
            } else {
                var leftInt = parseInt(elem.style.left);
                if (isNaN(leftInt)) {
                    leftInt = 0;
                }
                return leftInt;
            }
        }
    }
    return 0;
}

/*
Gets the width (pixels) of the element
with specified ID in the specified window.
*/
function getElemByIdWidth( theWin, id ) {
    return getElemWidth( getElemById(theWin, id) );
}

/*
Gets the width (pixels) of the specified element object.
*/
function getElemWidth( elem ) {
    if (elem) {
        if (elem.style) {
            if (bIE|| bOPERA) {
                return elem.style.pixelWidth;
            } else {
                var wInt = parseInt(elem.style.width);
                if (isNaN(wInt)) {
                    wInt = 0;
                }
                return wInt;
            }
        }
    }
    return 0;
}

/*
Gets the height (pixels) of the element
with specified ID in the specified window.
*/
function getElemByIdHeight( theWin, id ) {
    return getElemHeight( getElemById(theWin, id) );
}

/*
Gets the height (pixels) of the specified element object.
*/
function getElemHeight( elem ) {
    if (elem) {
        if (elem.style) {
            if (bIE|| bOPERA) {
                return elem.style.pixelHeight;
            } else {
                var hInt = parseInt(elem.style.height);
                if (isNaN(hInt)) {
                    hInt = 0;
                }
                return hInt;
            }
        }
    }
    return 0;
}

/*
Sets the opacity of the element
with specified ID in the specified window.
Opacity values : 0=transparent, 100=fully opaque
*/
function setElemByIdOpacity( theWin, id , opacity ) {
    setElemOpacity( getElemById(theWin, id), opacity );
}

/*
Sets the opacity of the element, if supported by the browser.
Opacity values : 0=transparent, 100=fully opaque
*/
function setElemOpacity( elem, opacity ) {
    if (elem) {
        if (bIE) {
            if ( document.getElementById ) {  // IE 5+
                elem.style.filter="Alpha(opacity="+opacity+")";
            }
        } else if (bOPERA) {
            // Don't know if its supported on Opera yet
        } else {  // Mozilla
            elem.style.MozOpacity = opacity/100;
        }
    }
}

/*
Returns true if val is a number and
    min <= val <= max
Otherwise returns false.
*/
function isIntegerInRange( val, min, max ) {
    if (!/^\-?\d+$/i.test(val)) {
        return false;
    }

    if (val < min || val > max) {
        return false;
    }

    return true;
}

/*
  Gets event's X offset relative to Superweb's "top" window.
*/
function getEventXOffsetFromSuperwebTop( evt, evtWin ) {
    var evtWinToSWXOffset = getWindowScreenXPos( evtWin ) -  getWindowScreenXPos( top.superwebTop );
    return evt.clientX + evtWinToSWXOffset;
}

/*
  Gets event's Y offset relative to Superweb's "top" window.
*/
function getEventYOffsetFromSuperwebTop( evt, evtWin ) {
    var evtWinToSWYOffset = getWindowScreenYPos( evtWin ) -  getWindowScreenYPos( top.superwebTop );
    return evt.clientY + evtWinToSWYOffset;
}

/*
 Gets the target element of an event. The target is always the
 element that the event originally happens on.
*/
function getEventTarget( evt ) {
    var eTgt = null;
    if ( evt.target ) {
        eTgt = evt.target;
    } else if ( evt.srcElement ) {
        eTgt = evt.srcElement;
    }
    return eTgt;
}

/*
  Gets the x screen position of a window.
*/
function getWindowScreenXPos( win ) {
    if (!isNaN(win.screenX)) {
        return win.screenX;
    }
    return win.screenLeft;
}

/*
  Gets the y screen position of a window.
*/
function getWindowScreenYPos( win ) {
    if (!isNaN(win.screenY)) {
        return win.screenY;
    }
    return win.screenTop;
}

/*
  Gets X offset of an element from the document's left edge.
*/
function getXOffsetFromDocument( elem ) {
    if ( elem==document) {
        return 0;
    }
    var offset = elem.offsetLeft;
    var parent = elem.offsetParent;
    while ((parent!=null) && (parent!=document))
    {
        offset = offset + parent.offsetLeft;
        parent = parent.offsetParent;
    }
    return offset;
}

/*
  Gets Y offset of an element from the document's top edge.
*/
function getYOffsetFromDocument( elem ) {
    if ( elem==document) {
        return 0;
    }
    var offset = elem.offsetTop;
    var parent = elem.offsetParent;
    while ((parent!=null) && (parent!=document))
    {
        offset = offset + parent.offsetTop;
        parent = parent.offsetParent;
    }
    return offset;
}

/*
  Checks if specified element contains coordinates xpos,ypos
  relative to the top-left corner of the document.
*/
function isElemContainsPoint( elem, xpos, ypos ) {
    var elemX = getXOffsetFromDocument(elem);
    var elemY = getYOffsetFromDocument(elem);
    if ( (xpos<elemX) || (xpos>(elemX+elem.offsetWidth))) {
        return false;
    }
    if ( (ypos<elemY) || (ypos>(elemY+elem.offsetHeight))) {
        return false;
    }
    return true;
}

/*
Truncates a string if it is longer than specified maxlen.
*/
function truncateString(str, maxlen) {
    if (str.length>maxlen) {
        if (maxlen>3) {
            return str.substr(0, maxlen-3)+"...";
        } else {
            return "...";
        }
    }
    return str;
}

/*
   This is my simple solution to a problem that has been
   bugging Web programmers since eternity :
   How to submit a form and replace the entry in history so that
   Back button doesn't bring you back to the original form?

   My solution is to construct a normal request equivalent to
   form's GET method, and send it using location.replace().
   Restrictions:
   - Make sure the action can process GET. If your service assumes POST only, it won't work.
   - Because its GET, there is a size restriction on amount of parameters.

   Note: Like form.submit(), this function will NOT call form.onsubmit().

   WARNING: Make sure your form doesn't resubmit again. For example, if you call
   submitFormNoHistory() from the form's onsubmit(), make sure you return false.

   Parameters:
   form - Form object to submit
   target - Window object as target for the form
   moreParams - Additional parameters to be submitted, must start with &, e.g. "&x=5"
*/
function submitFormNoHistory(form, target, moreParams) {    
	var urlStr = generateURLForGetSubmit(form, moreParams);

    var targetWin = self;
    if (target) {
        targetWin = target;
    }

    targetWin.location.replace(urlStr);    
}

function generateURLForGetSubmit(form, moreParams) {
	var rawAction = self.location;
    if (form.action) {
        rawAction = form.action;
    }
    
    var params = "";
    if (form.elements) {
        var prefix = ( rawAction.indexOf("?")==-1 ) ? "?" : "&";

        for (var i=0; i<form.elements.length; i++) {
            var elem = form.elements[i];
            if (elem.name) {
                if (elem.type == 'radio' || elem.type == 'checkbox'){
                    if (!elem.checked) continue;
                }
                params = params+prefix+escape(elem.name)+"=";
                if (elem.value) {
                    if (elem.value!=null) {
                        params = params+escape(elem.value);
                    }
                }
                prefix = "&";
            }
        }
    }

    if (moreParams) {
        params = params+moreParams;
    }
    
    return rawAction+params;
}


/*
This implements a simple mouse over effect for an image.
The image file name is derived from the <img> element name.
*/
function imgOver( imgElem, path ) {
    if ((path != null) && (path != ""))
    {
        imgElem.src=path+"/images/"+imgElem.name+"-over.gif";
    } else {
        imgElem.src="images/"+imgElem.name+"-over.gif";
    }
}

/*
This implements a simple mouse out effect for an image.
The image file name is derived from the <img> element name.
*/
function imgOut( imgElem, path ) {
    if ((path != null) && (path != ""))
    {
        imgElem.src=path+"/images/"+imgElem.name+".gif";
    } else {
        imgElem.src="images/"+imgElem.name+".gif";
    }
}

/**
* This converts text into unicode so that it can be sent via a URL.
*/
function convertText(source){
    result = '';
    for (i=0; i<source.length; i++){
        result += source.charCodeAt(i).toString(16) + '~';
    }
    var slashes=result.split("~")
    var buildU
    var finalU=""
    for(i=0;i<slashes.length-1;i++){
        switch(slashes[i].length){
            case 1:
            buildU="\\u000"+slashes[i]
            break
            case 2:
            buildU="\\u00"+slashes[i]
            break
            case 3:
            buildU="\\u0"+slashes[i]
            break
            case 4:
            buildU="\\u"+slashes[i]
            break
        }
        finalU+=buildU
    }
    return finalU;
}

/**
* This function is use for convert a date string to a Date object.
*/
function convertDate(dateStr, datePattern) {
    if (!datePattern) datePattern = "yyyy-MM-dd";
    var MONTH = "MM"; var DAY = "dd"; var YEAR = "yyyy";
    var orderMonth = datePattern.indexOf(MONTH);
    var orderDay = datePattern.indexOf(DAY);
    var orderYear = datePattern.indexOf(YEAR);
    if ((orderDay < orderYear && orderDay > orderMonth)) {// MM-dd-yyyy
        var iDelim1 = orderMonth + MONTH.length;
        var iDelim2 = orderDay + DAY.length;
        var delim1 = datePattern.substring(iDelim1, iDelim1 + 1);
        var delim2 = datePattern.substring(iDelim2, iDelim2 + 1);
        if (iDelim1 == orderDay && iDelim2 == orderYear) {
            dateRegexp = new RegExp("^(\\d{1,2})(\\d{1,2})(\\d{4})$");
        } else if (iDelim1 == orderDay) {
            dateRegexp = new RegExp("^(\\d{1,2})(\\d{1,2})[" + delim2 + "](\\d{4})$");
        } else if (iDelim2 == orderYear) {
            dateRegexp = new RegExp("^(\\d{1,2})[" + delim1 + "](\\d{1,2})(\\d{4})$");
        } else {
            dateRegexp = new RegExp("^(\\d{1,2})[" + delim1 + "](\\d{1,2})[" + delim2 + "](\\d{4})$");
        }
        var dateMatched = dateRegexp.exec(dateStr);
        if (dateMatched != null && isValidDate(dateMatched[3], dateMatched[1], dateMatched[2])) {
            return new Date(dateMatched[3], dateMatched[1] - 1, dateMatched[2]);
        } else {
            return null;
        }
    } else if ((orderMonth < orderYear && orderMonth > orderDay)) {// dd-MM-yyyy
        var iDelim1 = orderDay + DAY.length;
        var iDelim2 = orderMonth + MONTH.length;
        var delim1 = datePattern.substring(iDelim1, iDelim1 + 1);
        var delim2 = datePattern.substring(iDelim2, iDelim2 + 1);
        if (iDelim1 == orderMonth && iDelim2 == orderYear) {
            dateRegexp = new RegExp("^(\\d{1,2})(\\d{1,2})(\\d{4})$");
        } else if (iDelim1 == orderMonth) {
            dateRegexp = new RegExp("^(\\d{1,2})(\\d{1,2})[" + delim2 + "](\\d{4})$");
        } else if (iDelim2 == orderYear) {
            dateRegexp = new RegExp("^(\\d{1,2})[" + delim1 + "](\\d{1,2})(\\d{4})$");
        } else {
            dateRegexp = new RegExp("^(\\d{1,2})[" + delim1 + "](\\d{1,2})[" + delim2 + "](\\d{4})$");
        }
        var dateMatched = dateRegexp.exec(dateStr);
        if (dateMatched != null && isValidDate(dateMatched[3], dateMatched[2], dateMatched[1])) {
            return new Date(dateMatched[3], dateMatched[2] - 1, dateMatched[1]);
        } else {
            return null;
        }
    } else if ((orderMonth > orderYear && orderMonth < orderDay)) {// yyyy-MM-dd
        var iDelim1 = orderYear + YEAR.length;
        var iDelim2 = orderMonth + MONTH.length;
        var delim1 = datePattern.substring(iDelim1, iDelim1 + 1);
        var delim2 = datePattern.substring(iDelim2, iDelim2 + 1);
        if (iDelim1 == orderMonth && iDelim2 == orderDay) {
            dateRegexp = new RegExp("^(\\d{4})(\\d{1,2})(\\d{1,2})$");
        } else if (iDelim1 == orderMonth) {
            dateRegexp = new RegExp("^(\\d{4})(\\d{1,2})[" + delim2 + "](\\d{1,2})$");
        } else if (iDelim2 == orderDay) {
            dateRegexp = new RegExp("^(\\d{4})[" + delim1 + "](\\d{1,2})(\\d{1,2})$");
        } else {
            dateRegexp = new RegExp("^(\\d{4})[" + delim1 + "](\\d{1,2})[" + delim2 + "](\\d{1,2})$");
        }
        var dateMatched = dateRegexp.exec(dateStr);
        if (dateMatched != null && isValidDate(dateMatched[1], dateMatched[2], dateMatched[3])) {
            return new Date(dateMatched[1], dateMatched[2] - 1, dateMatched[3]);
        } else {
            return null;
        }
    } else {
        return null;
    }
}

function isValidDate(year, month, day) {
    if (month < 1 || month > 12) {
        return false;
    }
    if (day < 1 || day > 31) {
        return false;
    }
    if ((month == 4 || month == 6 || month == 9 || month == 11) && (day == 31)) {
        return false;
    }
    if (month == 2) {
        var leap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
        if (day>29 || (day == 29 && !leap)) {
            return false;
        }
    }
    return true;
}