/*

GH Software Java Function Library
(c) 2006-2008
http://www.ghsoftware.dk

    *  License: LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
    *  
    *  This library is free software; you can redistribute         *
    *  it and/or modify it under the terms of the GNU              *
    *  Lesser General Public License as published by the           *
    *  Free Software Foundation; either version 2.1 of the         *
    *  License, or (at your option) any later version.             *
    *                                                              *
    *  This library is distributed in the hope that it will        *
    *  be useful, but WITHOUT ANY WARRANTY; without even the       *
    *  implied warranty of MERCHANTABILITY or FITNESS FOR A        *
    *  PARTICULAR PURPOSE. See the GNU Lesser General Public       *
    *  License for more details.                                   *
    *                                                              *

This implementation contains functions by
    * tuckey.org
    *

*/
    var GHS_WindowModel = null;
    var GHS_ToolWindow = null;
	
	
	/**
	 * @alias UpdateOptionsSelect
	 * @param {Object} Source
	 * @param {Object} CallBackFunction
	 */
    function UpdateOptionsSelect(Source, CallBackFunction)
    {
        var ResultString = "";

        var SelList = document.getElementById(Source);

        for(var i = 0; i < SelList.length; i++) 
        {
            if ((SelList.options[i] != null)) 
            {
                if(ResultString.length > 0) ResultString += ";"
                ResultString += SelList.options[i].value;
            }
        }
            
        eval(CallBackFunction + "('" + ResultString + "')");
    }
    
        
function ghs_showclasscontnet()
{
    var CurrentSelected = document.getElementById("ghs_classselect").value;
    if(CurrentSelected && CurrentSelected != "-1")
    {
        document.getElementById("class_showcontent").innerHTML = document.getElementById("classid_" + CurrentSelected).innerHTML;
    }
    else document.getElementById("class_showcontent").innerHTML = "";
}

function ghs_selectclass(FunctionToCall)
{
    eval(FunctionToCall + '(' + document.getElementById("ghs_classselect").value + ')'); 
}
        


function FlipBits(Input) 
{
    var Output = 0;
    for(var i=31;i>=0;i--)
    {
        if(Input & (1<<i)) Output = (Output << 1); //From 1 to 0
        else Output = (Output << 1) + 0x1; //From 0 to 1
    };
    return Output;
}


function ChangeFixedTopRight(DivName, FromTop, FromRight, Width)
{
    var DivTag = document.getElementById(DivName);
    if(DivTag.style.cssText.length > 0)
    {
        DivTag.style.cssText = "";
        document.getElementById("X" + DivName).innerHTML = "[X]";
    }
    else
    {
        DivTag.style.cssText = "position: fixed; top: " + FromTop + "; right: " + FromRight + "; width: " + Width;
        document.getElementById("X" + DivName).innerHTML = "[O]";
    }
}

function validateHTML5Doc()
{
    var inputelements = document.getElementsByTagName("input"); 
    GHS_EvaluateErrorCount = 0;
    for (var i = 0; i < inputelements.length; i++) 
    { 
        if(inputelements[i].getAttribute("type5") )
        {
            inputelements[i].BValue = inputelements[i].value;
            validateHTML5(inputelements[i].id);
        }
    }
}

var GHS_EvaluateErrorCount = 0;
var GHS_Revaluate = null;
function validateHTML5WithCallBack(InputElementByID, EvalOnSuccess)
{
    GHS_EvaluateErrorCount = 0;
    if(validateHTML5(InputElementByID) == true)
    {
        return eval(EvalOnSuccess.replace("[", "'").replace("]", "'"));
    }
    return false;
}

function validateHTML5(InputElementByID)
{
    var InputElement = null;
    if(InputElementByID == null) InputElement = GHS_Revaluate;
    else InputElement = document.getElementById(InputElementByID);
    
    if(!InputElement) return false;
    var ThisType = InputElement.getAttribute("type5");
    var Min = InputElement.getAttribute("min5");
    var Max = InputElement.getAttribute("max5");
    var Digits = InputElement.getAttribute("digit5");
    var ValidationError = 0;
    if(ThisType == "number" || ThisType == "currency")
    {
        if(Min && parseFloat(InputElement.value) < Min) ValidationError |= 0x1;
        if(Max && parseFloat(InputElement.value) > Max) ValidationError |= 0x2;
        if(isNaN(InputElement.value)) ValidationError |= 0x4;
        
        if(ValidationError == 0)
        {
            InputElement.value = round(InputElement.value, Digits);
        }
    }
    else     //Text
    {
        if(Min && InputElement.value.length < Min) ValidationError |= 0x10;
        if(Max && InputElement.value.length > Max) ValidationError |= 0x20;
    }
    
    if(ValidationError != 0)
    {
		if(InputElement.BValue != undefined && parseFloat(InputElement.BValue) != "NaN") InputElement.value = InputElement.BValue;
        else InputElement.value = Min;
        var Errormessage = "<small>";
        if(ValidationError & 0x1) Errormessage += "Input must be >= " + Min + ".";
        if(ValidationError & 0x2) Errormessage += "Input must be <= " + Max + ".";
        if(ValidationError & 0x4) Errormessage += "Input must be a number";
        if(ValidationError & 0x10) Errormessage += "Input must be at least " + Min + " characters.";
        if(ValidationError & 0x20) Errormessage += "Input must be at most " + Max + " characters.";
        Errormessage += "</small>";
        
        
        document.getElementById("validate_" + InputElement.id).innerHTML = Errormessage;
        InputElement.style.borderBottom = "2px solid red";
        
        if(GHS_Revaluate == null) window.setTimeout('validateHTML5(null)', 1000);
        GHS_Revaluate = InputElement;
        GHS_EvaluateErrorCount++;
        return false;
    }
    else
    {
        InputElement.BValue = InputElement.value;
        document.getElementById("validate_" + InputElement.id).innerHTML = ""; 
        InputElement.style.borderBottom = "";
        GHS_Revaluate = null;
        return true;
    }
    
//    alert(ThisType);
}

function round(num, digits)
{
    num = num.toString();
    var split = num.split(".");
    if(split.length > 1)
    {
		if(digits == 0) return split[0];
        return split[0] + "." + split[1].substr(0, parseInt(digits));
    }
    else return num;
}

//Check that the field length is > MinLength
function CheckTextLength(Input, MinLength, MaxLength)
{
    var BlockTarget = null;
    //if(BlockID != "null") BlockTarget = document.getElementById(BlockID);
    if((MinLength > -1 && Input.value.length < MinLength) || (MaxLength > -1 && Input.value.length > MaxLength))
    {
        Input.style.borderColor = 'red';
        return;
    }
    else
    {
        Input.style.borderColor = '';
        Input.title = Input.value;
    }
    
}

//Evaluate that an text field is a unsigned integer in the range: [0..MaxNumber]
function CheckUNumber(Input, MinNumber, MaxNumber)
{
 
    try
    {
        //alert("Min..Max: " + MinNumber + " -> " + MaxNumber);
        //if(isPositiveInteger(Input.value) == false )// || SortNumber > MaxNumber)
        var SortNumber = parseInt(Input.value);
        if(isNaN(SortNumber) || SortNumber < MinNumber || SortNumber > MaxNumber || Input.value != SortNumber)
        {
            Input.value = Input.title;
            Input.style.borderColor = 'red';
            return;
        }
        else
        {
            //Input.value = SortNumber;
            Input.style.borderColor = '';
            Input.title = Input.value;
        }
    }
    catch(e)
    {
        Input.value = Input.title;
        Input.style.borderColor = 'red';
    }
}

//Evaluate that an text field is a unsigned integer in the range: [0..MaxNumber]
function CheckDoubleNumber(Input, MinNumber, MaxNumber)
{
    try
    {
        //alert("Min..Max: " + MinNumber + " -> " + MaxNumber);
		if( isNaN(Input.value) ) 
		{
            Input.value = Input.title;
            Input.style.borderColor = 'red';
		}
		else
		{
            if( Input.value < MinNumber || Input.value > MaxNumber)
            {
                Input.value = Input.title;
                Input.style.borderColor = 'red';
                return;
            }
            else
            {
                //Input.value = SortNumber;
                Input.style.borderColor = '';
                Input.title = Input.value;
            }
		}
	} 
    catch(e)
    {
        Input.value = Input.title;
        Input.style.borderColor = 'red';
    }
}

function FlipVisible(FlipID)
{
    if(document.getElementById(FlipID).style.display == "none")
    {
        document.getElementById(FlipID).style.display = ""
    }
    else
    {
        document.getElementById(FlipID).style.display = "none"
    }
    
}

function SetVisible(ID_A, ID_B)
{
    if(document.getElementById(ID_A).style.display == "none")
    {
        document.getElementById(ID_A).style.display = ""
        document.getElementById(ID_B).style.display = "none"
    }
    else
    {
        document.getElementById(ID_B).style.display = ""
        document.getElementById(ID_A).style.display = "none"
    }
    
}

function SetVisibleMarker(ID_A, ID_B, Marker)
{
    SetVisible(ID_A, ID_B);
    if(document.getElementById(ID_A).style.display == "none") document.getElementById(Marker).value = ID_B;
    else document.getElementById(Marker).value = ID_A;
    
}

function List_GetSelectedText(TagName)
{
    var A = document.getElementById(TagName);
    if(A != null)
    {
        try
        {
            return A.options[A.selectedIndex].text;
        }
        catch(e)
        {
            //ups
        }
    }
    return "";
}


function MoveItem(ListFromName, ListToName)
{
    var ListTo = document.getElementById(ListToName);
    var ListFrom = document.getElementById(ListFromName);

   
    //Insert to target
    var len = ListFrom.options.length;
    for(var i = (len-1); i >= 0; i--) 
    {
        if ((ListFrom.options[i] != null) && (ListFrom.options[i].selected == true)) 
        {
            var P = new Option(ListFrom.options[i].text);
            P.value = ListFrom.options[i].value;

            ListTo.options[ListTo.length] = P;
            //ListTo.options[ListTo.length-1].selected = true;

            ListFrom.options[i] = null;
            break;
        }
    }
    
    SortListBox(ListTo);

}

function GetSelectValues(ListSourceName, Delimiter)
{
    return GetSelectedValues(ListSourceName, Delimiter);
//    var ListSource = document.getElementById(ListSourceName);
//    var TargetString = "";
//   
//    //Insert to target
//    var len = ListSource.options.length;
//    for(var i = 0; i< ListSource.options.length; i++) 
//    {
//        if(Delimiter == "[" || TargetString.length > 0) TargetString += Delimiter;
//        TargetString += ListSource.options[i].value;
//        if(Delimiter == "[") TargetString += "]";
//    }
//    
//    return TargetString;
}

function GetSelectedValues(ListSourceName, Delimiter)
{
    var ListSource = document.getElementById(ListSourceName);
    var TargetString = "";
   
    //Insert to target
    var len = ListSource.options.length;
    for(var i = 0; i< ListSource.options.length; i++) 
    {
        if(ListSource.options[i].selected == true)
        {
            if(Delimiter == "[" || TargetString.length > 0) TargetString += Delimiter;
            TargetString += ListSource.options[i].value;
            if(Delimiter == "[") TargetString += "]";
        }
    }
    
    return TargetString;
}


function UnSelectValues(ListSourceName)
{
    var ListSource = document.getElementById(ListSourceName);
    for(var i = (ListSource.options.length-1); i >= 0; i--) 
    {
        ListSource.options[i].selected = false;
    }
}

function SortListBox(ListBoxToSort) 
{
    arrTexts = new Array();
    for(i=0; i<ListBoxToSort.length; i++)  
    {
        arrTexts[i] = ListBoxToSort.options[i].text + "|" + ListBoxToSort.options[i].value;
    }
    arrTexts.sort();
    for(i=0; i<ListBoxToSort.length; i++)  
    {
        var T = arrTexts[i].split("|");
        ListBoxToSort.options[i].text = T[0];
        ListBoxToSort.options[i].value = T[1];
    }
}


//(c) - tuckey.org
function countLines(strtocount, cols) 
{
    var hard_lines = 1;
    var last = 0;
    while ( true ) {
        last = strtocount.indexOf("\n", last+1);
        hard_lines ++;
        if ( last == -1 ) break;
    }
    var soft_lines = Math.round(strtocount.length / (cols-1));
    var hard = eval("hard_lines  " + unescape("%3e") + "soft_lines;");
    if ( hard ) soft_lines = hard_lines;
    return soft_lines;
}

//(c) - org. implementation: tuckey.org
function ResizeTextArea(TagID) 
{
    var ResizeMe = document.getElementById(TagID);
        var NewCount = countLines(ResizeMe.value,ResizeMe.cols); //Mod by GH 
        if(NewCount <= 16)
        {
            ResizeMe.rows = NewCount;
        }
        
}

    try
    {
        Node.prototype.swapNode = function (node)   //Enable node-swapping in Gecko
        {
            var nextSibling = this.nextSibling;
            var parentNode = this.parentNode;
            node.parentNode.replaceChild(this, node);
            parentNode.insertBefore(node, nextSibling);  
        }
    }
    catch(e)
    {
    }
    
    function SwapDivOrder(MoveNodeID, MoveWay)
    {
        var MoveNode = document.getElementById(MoveNodeID);
        var OtherNode = null;
        
        if(MoveWay == -1) //Up
        {
            OtherNode = MoveNode.previousSibling;
        }
        else //Down        
        {
            OtherNode = MoveNode.nextSibling;
            var Temp = MoveNode;    //Otherwise Gecko gets confused
            MoveNode = OtherNode;
            OtherNode = Temp;
        }
        
        if(OtherNode && MoveNode)
        {
            MoveNode.swapNode(OtherNode);
            return true;
        } 
        return false;
    }
    
    function SetUIStyle(ThemeStyle)
    {
        GHS_Global.SetUITheme(ThemeStyle, SetUIStylePost);
    }
    function SetUIStylePost(res)
    {
        if(!res.error)
        {
            self.status = "Ok: The theme will change at the next user interface reload";
        }
        else self.status = "Error: Could not set theme!";
    }
    
    function SyncHTMLData(ElementID, Value)
    {
        if(document.getElementById(ElementID).value != undefined)
        {
            if(Value)
            {
                document.getElementById(ElementID).value = Value;
            }
            else return document.getElementById(ElementID).value;
        }
        else 
        {
            if(Value)
            {
                document.getElementById(ElementID).innerHTML = Value;
            }
            else return document.getElementById(ElementID).innerHTML;
        }
    }    

    function AjaxUpdateHTMLContent(/* Data2DOM or List<Data2DOM> */ res)
    {
        if(res && res.value) 
        {
            if(res.value.constructor.toString().indexOf("Array") == -1)
            {
                //Not an array
                UpdateHTMLContent(res.value);
            }
            else
            {
                //Array
                for(iA = 0; iA < res.value.length; iA++)
                {
                    UpdateHTMLContent(res.value[iA]);
                }
            }
        }
    }

    function UpdateHTMLContent(/* Data2DOM */ Source)
    {
        if(!document.getElementById(Source.elementId))
        {
            return false;
        }
        document.getElementById(Source.elementId).innerHTML = Source.innerHTML; 
        document.getElementById(Source.elementId).style.display = "";

        if(Source.Script != null) 
        {
            eval(Source.Script);
        }
        return true;
    }

