// wli-erp javascript file
// Global variables

var mousepos = null;
var pagesize = null;
var windowsize = null;
var isIE = (navigator.userAgent.indexOf("MSIE") >= 0);

// get mouse position
if (document.layers) { // Netscape
    document.captureEvents(Event.MOUSEMOVE);
    document.onmousemove = captureMousePosition;
} else if (document.all) { // Internet Explorer
    document.onmousemove = captureMousePosition;
} else if (document.getElementById) { // Netcsape 6
    document.onmousemove = captureMousePosition;
}

function captureMousePosition(e) {
    if(!e) 
    {
        e = window.event; 
    } 
    if(!e||(typeof(e.pageX)!='number'&&typeof(e.clientX)!='number')) 
    { 
        mousepos = {x:0,y:0};
    }
    
    if (document.layers) {
        if(e)
        {
            mousepos = {x:e.pageX,y:e.pageY};
        }
    } 
    else if (document.all && document.body) 
    {
        mousepos = {x:e.clientX+document.documentElement.scrollLeft,y:e.clientY+document.documentElement.scrollTop};
    } 
    else if (document.getElementById) 
    {
        if(e)
        {
            mousepos = {x:e.pageX+window.pageXOffset,y:e.pageY+window.pageYOffset};
        }
    }
    capturePageDimensions();
}

function capturePageDimensions(){
	if(document.body){
	    // code based on lightbox.js
	    var xScroll, yScroll;
    	
	    if (window.innerHeight && window.scrollMaxY) {	
		    xScroll = document.body.scrollWidth;
		    yScroll = window.innerHeight + window.scrollMaxY;
	    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		    xScroll = document.body.scrollWidth;
		    yScroll = document.body.scrollHeight;
	    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		    xScroll = document.body.offsetWidth;
		    yScroll = document.body.offsetHeight;
	    }
    	
	    var windowWidth, windowHeight;
	    if (self.innerHeight) {	// all except Explorer
		    windowWidth = self.innerWidth;
		    windowHeight = self.innerHeight;
	    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		    windowWidth = document.documentElement.clientWidth;
		    windowHeight = document.documentElement.clientHeight;
	    } else if (document.body) { // other Explorers
		    windowWidth = document.body.clientWidth;
		    windowHeight = document.body.clientHeight;
	    }	
    	
	    // for small pages with total height less then height of the viewport
	    if(yScroll < windowHeight){
		    pageHeight = windowHeight;
	    } else { 
		    pageHeight = yScroll + 50;
	    }

	    // for small pages with total width less then width of the viewport
	    if(xScroll < windowWidth){	
		    pageWidth = windowWidth;
	    } else {
		    pageWidth = xScroll;
	    }

        var scrollLeft, scrollTop;
		if(window.pageXOffset) {
		    scrollLeft = window.pageXOffset;
		    scrollTop = window.pageYOffset;
		}
		else if(document.documentElement) {
		    scrollLeft = document.documentElement.scrollLeft;
		    scrollTop = document.documentElement.scrollTop;
		}
		else if(document.body) {
		    scrollLeft = document.body.scrollLeft;
		    scrollTop = document.body.scrollTop;
		}
		
        windowsize = {
            width:pageWidth,
            height:pageHeight,
            windowWidth:windowWidth,
            windowHeight:windowHeight,
            scrollTop:scrollTop,
            scrollLeft:scrollLeft
        }
    }
}

// -----------------------------------------------------------------------------------

function GetPageScroll(){

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}
	return yScroll;
}

function SetPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

    pageHeight += 30;
    
	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}

    pagesize = {width:pageWidth,height:pageHeight};
    windowsize = {width:windowWidth,height:windowHeight};
}

function BeginRequestHandler()
{
    $get("loadingbox").style.display = "block";
}

function EndRequestHandler()
{
    $get("loadingbox").style.display = "none";
}

function ChangeHover(item,hover,cssclass)
{
	if(hover)
	{
		if(!Sys.UI.DomElement.containsCssClass(item, cssclass)) {
			Sys.UI.DomElement.addCssClass(item, cssclass);
		}
	}
	else
	{
		if(Sys.UI.DomElement.containsCssClass(item, cssclass)) {
			Sys.UI.DomElement.removeCssClass(item, cssclass);
		}
	}
}

function GetElementsByClassName(oElm, strTagName, strClassName){
    var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    strClassName = strClassName.replace(/\-/g, "\\-");
    var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
    var oElement;
    for(var i=0; i<arrElements.length; i++){
        oElement = arrElements[i];      
        if(oRegExp.test(oElement.className)){
            arrReturnElements.push(oElement);
        }   
    }
    return (arrReturnElements)
}

function getStyle( element, style ) 
{ 
	var value = element.style[style]; 
    if (!value) { 
      if (document.defaultView && document.defaultView.getComputedStyle) { 
		var css = document.defaultView.getComputedStyle(element, null); 
        value = css ? css.getPropertyValue(style) : null; 
      } else if (element.currentStyle) { 
		value = element.currentStyle[style]; 
      } 
     }
     return  value; 
}
//Dialog functions
var dialogtargetid = null;

function OpenDialog(id,width,height,title,closeaction,infoaction)
{
    dialogtargetid = id;
    
    var dialog = $get("maindialog");
    var inner = $get("maindialoginner");
    var contentholder = $get("maindialogcontent");
    var dialogtitle = $get("maindialogtitle");
    var closebutton = $get("maindialogclosebutton");
    var infobutton = $get("maindialoginfobutton");
    
    var target = $get(dialogtargetid);
    
    // set height and width of the dialog
    inner.style.width = width + "px";
    inner.style.height = height + "px";
    
    //append inner content for dialog
    if(target)
    {
        for(var i=target.childNodes.length;i>0;i--)
        {
            contentholder.appendChild(target.childNodes[i-1]);
        }
    }
    else
    {
        var errordiv = ($get("errordiv")?$get("errordiv"):document.createElement('div'));
        errordiv.id = "errordiv";
        errordiv.className = "maindialogerror";
        errordiv.innerHTML = "target element not found";
        contentholder.appendChild(errordiv);
    }
    
    //set title
    if(title)
    {
        dialogtitle.innerHTML = title;
    }
    else
    {
        dialogtitle.innerHTML = "Softportal";
    }
    
    // set closeaction
    if(closeaction)
    {
        closebutton.onclick = closeaction;
    }
    else
    {
        closebutton.onclick = CloseDialog;
    }
    
    // set infoaction
    if(infoaction)
    {
        infobutton.onclick = infoaction;
        infobutton.style.display = "block";
    }
    else
    {
        infobutton.style.display = "none";
    }
    
    // set dialog visible
    dialog.style.display = "block";
    inner.style.display = "block";
    
    //add floating behavior
    var floatingBehavior = null;

    var draggable = $get('maindialogdraggable');
    if(draggable){
        if(inner._behaviors != null) {
            floatingBehavior = inner._behaviors[0];
            floatingBehavior.set_handle(draggable);
        }
        else
        {
            floatingBehavior = new Sys.Preview.UI.FloatingBehavior(inner);
            floatingBehavior.set_handle(draggable);
            floatingBehavior.initialize();
            floatingBehavior.drop = CheckFloatingPosition;
        }
    }
    
    Resize();
}

function CheckFloatingPosition()
{
    var dialog = $get('maindialoginner');
    if(dialog)
    {
        var dt = getStyle(dialog,'top');
        var dl = getStyle(dialog,'left');
        
        var resize = false;
        
        if(dt.length>0) {
            var t = parseInt(dt.substring(0,dt.length-2));
            if(t + 150 > windowsize.height)
            {
                dialog.style.top = windowsize.height - 150 + 'px';
                resize = true;
            }
            else
            {
                if(t < 0)
                {
                    dialog.style.top = 0 + 'px';
                }
            }
        }
        if(dl.length>0 && resize == false) {
            var l = parseInt(dl.substring(0,dl.length-2));
            if(l < 0)
            {
                dialog.style.left= 0 + 'px';
            }
            else
            {
                if(l+150 > windowsize.width)
                    dialog.style.left = windowsize.width - 150 + 'px';
            }
        }
    }
}

function CloseDialog()
{
    var dialog = $get("maindialog");
    var inner = $get("maindialoginner");
    var contentholder = $get("maindialogcontent");
    var closebutton = $get("maindialogclosebutton");
    var infobutton = $get("maindialoginfobutton");
    
    var target = $get(dialogtargetid);
    
    //hide dialog
    dialog.style.display = "none";
    inner.style.display = "none";
    
    // move innercontent back to its holder
    if(target)
    {
        for(var i=contentholder.childNodes.length;i>0;i--)
        {
            target.appendChild(contentholder.childNodes[i-1]);
        }
    }
    else
    {
        contentholder.removeChild($get("errordiv"));
    }
    
    //reset actions
    closebutton.onclick = null; 
    infobutton.onclick = null;
}

function Resize()
{
    if($get('maindialog') && getStyle($get('maindialog'),"display")!="none") {
        capturePageDimensions();
        
        var dialog = $get("maindialog");
        var inner = $get("maindialoginner");
        var contentholder = $get("maindialogcontent");
    
        //set height and width of the dialog cover
        dialog.style.width = windowsize.width + "px";
        dialog.style.height = windowsize.height + "px";
        
        var dialogwidth = parseInt(inner.style.width.replace('px',''));
        var dialogheight = parseInt(inner.style.height.replace('px',''));
        
        // set position of the dialog centered
        inner.style.left = Math.floor(windowsize.windowWidth / 2 - (dialogwidth/2)) + "px";
        inner.style.top = Math.floor(windowsize.scrollTop + (windowsize.windowHeight / 2) - (dialogheight/2)) + "px";
        
        //set height of content holder
        contentholder.style.height = (dialogheight-30) + "px";
    }
}

/*
##########################
    Order
##########################
*/

function CheckQuantity(dropdown)
{
    if(dropdown.value.length > 0)
    {
        SetQuantity(dropdown.value);
    }
    else
    {
        ResetQuantityValue();
    }
}

function ResetQuantityValue()
{
    $get("bondquantity").innerHTML = 0;
    $get("taxquantity").innerHTML = 0;
    $get("freequantity").innerHTML = 0;
}

function SetQuantity(id)
{
    if(id) {
        wli.erp.webui.UiService.GetProductQuantityAvailable(id,CheckQuantityComplete);
    }
    else
    {
        ResetQuantityValue();
    }
}

function CheckQuantityComplete(res)
{
    $get("bondquantity").innerHTML = res.Bond;
    $get("taxquantity").innerHTML = res.Tax;
    $get("freequantity").innerHTML = res.Free;
    $get("samplequantity").innerHTML = res.Sample;
}

function CheckQuantityText(textbox,button,statedd,editval,editstate,pbref)
{
    var value = Math.abs(textbox.value);
    var state = statedd.value;
    var bondquantity = $get("bondquantity");
    var taxquantity = $get("taxquantity");
    var freequantity = $get("freequantity");
    var samplequantity = $get("samplequantity");
    
    var bond = Math.abs(bondquantity.innerHTML);
    var tax = Math.abs(taxquantity.innerHTML);
    var free = Math.abs(freequantity.innerHTML);
    var sample = Math.abs(samplequantity.innerHTML);
    
    if(value>0)
    {
        var showbutton = true;
        
        //reset
        bondquantity.style.color = "#000000";
        taxquantity.style.color = "#000000";
        freequantity.style.color = "#000000";
        samplequantity.style.color = "#000000";
        
        if(state=="Bond")
        {
            if(editstate==state)
            {
               value -= editval;
            }
            if(value>bond)
            {
                showbutton = false;
                bondquantity.style.color = "#ff0000";
            }
        }
        else if(state=="Tax") 
        {
            if(editstate==state)
            {
               value -= editval;
            }
            
            if(value>tax)
            {
                showbutton = false;
                taxquantity.style.color = "#ff0000";                    
            }
        }
        else if(state=="Free")
        {
            if(editstate==state)
            {
               value -= editval;
            }
            if(value>free)
            {
                showbutton = false;
                freequantity.style.color = "#ff0000";
            }
        }
        else if(state=="Sample")
        {
            if(editstate==state)
            {
               value -= editval;
            }
            if(value>sample)
            {
                showbutton = false;
                samplequantity.style.color = "#ff0000";
            }
        }
        
        if(showbutton)
        {
            //todo: use disabled but prevent tabbing to controls under the overlay
            button.style.display="block";
            //button.disabled=false;
            
            if(pbref)
            { 
                window.setTimeout(pbref,0);   
            }
        }
        else
        {
            button.style.display="none";
            //button.disabled=false;
        }
    }
    else
    {
        button.style.display="none";
    }
}

var searchtimer = null;
function Search(textbox)
{
    clearTimeout(searchtimer);
    searchtimer = setTimeout("PerformSearch('" + textbox.value + "')",500);
}

function PerformSearch(value)
{
    if(value.length>=3)
    {
        BeginRequestHandler();
        wli.erp.webui.UiService.SearchData(value,PerformSearchComplete);
    }
}

function PerformSearchComplete(value)
{
    if(value.length>0)
    {
        $get("searchresultinner").innerHTML = value;
        $get("searchresult").style.display = "block";
    }
    else
    {
        HideSearch();
    }
    
    EndRequestHandler();
}
function HideSearch()
{
    $get("searchresult").style.display = "none";
}

function CheckUniqueProductCode(txt,productid)
{
    var value = txt.value;
    wli.erp.webui.UiService.CheckUniqueProductCode(value,productid,CheckUniqueProductCodeComplete);
}

function CheckUniqueProductCodeComplete(res)
{
    if(res)
    {
        // code is unique don't do anything
    }
    else
    {
        // inform user
        alert('Invalid product code. The code entered exists in the database.')
    }
}

var invoicenumbertextbox;
function CheckInvoiceNumber(txt,oldvalue)
{
    invoicenumbertextbox = txt;
    var value = txt.value;

    if (oldvalue != null) {
        if (oldvalue.toString().toLowerCase() == value.toString().toLowerCase()) {
            txt.style.border = "1px solid #c7c7c7";
            return;
        } 
    }
    
    if(value.length>=3)
    {
        wli.erp.webui.UiService.CheckInvoiceNumber(value,CheckInvoiceNumberComplete);
    }
}
function CheckInvoiceNumberComplete(res)
{
    if(res==true)
    {
        alert("The invoice number allready exists in the database.");
        if(invoicenumbertextbox!=null){invoicenumbertextbox.style.border="2px solid red";}
    }
    else
    {
        if(invoicenumbertextbox!=null){invoicenumbertextbox.style.border="2px solid green";}
    }
}
