/// <reference path="json2.js" />

function unescapeHTML(html) {
    var htmlNode = document.createElement("DIV");
    htmlNode.innerHTML = html;
    if(htmlNode.innerText)
        return htmlNode.innerText; // IE
    return htmlNode.textContent; // FF
}

function jax(Ddata, Uurl, Ssuccess)
{
    if (Ddata == null) {Ddata = {};}

    $.ajax({
        url: Uurl,
        cache: false,
        type: "POST",
        data: Ddata,
        dataType: "xml",
        //        beforeSend: function(XMLHttpRequest) {
        //            if (this.data == null) {
        //            this.data = {};
        //            }
        //            
        //        
        //        },
        success: function(msg) { this.newmsg = msg; },
        complete: function(XMLHttpRequest, textStatus)
        {
            if (XMLHttpRequest.status != 200 & XMLHttpRequest.status != 500)
            {
                if (XMLHttpRequest.status == 12031)
                {
                    alert('We have encountered an error thats unique to certain older versions of Internet Explorer 6 please upgrade your browser or wait 300 seconds and try again.')
                }
                else if (XMLHttpRequest.status == 403)
                {
                    alert('Sorry too many people are logged into the system right now (development server can only handle 3 concurrent logons)');
                }
                else if (XMLHttpRequest.status == 0)
                {
                    //alert('Sorry the system has been restarted you may have to log back in)'); 
                }
                else
                {
                    alert(XMLHttpRequest.status);
                }
            }
            else
            {
                if (window.location.href.indexOf("/login/default.htm") > -1)
                {
                    Ssuccess(this.newmsg);
                }
                else
                {
                    if (XMLHttpRequest.getResponseHeader("Content-Location"))
                    {
                        if (XMLHttpRequest.getResponseHeader("Content-Location").indexOf("/login/default.htm") > -1)
                        {
                            alert("You have logged in with a different role and will be redirected to the login page");
                            window.location = "/login";
                        }
                    }
                    else
                    {
                        Ssuccess(this.newmsg);
                    }
                }
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown)
        {
            if (XMLHttpRequest.status != 200 && XMLHttpRequest.status != 403 && XMLHttpRequest.status != 0 && XMLHttpRequest.status != 12031)
            {
                if (XMLHttpRequest.responseText.indexOf("Could not load file or assembly 'mcpV2' or one of its dependencies.") > -1)
                {
                    //try again in 2 seconds
                    //window.tryAgain = jax(Ddata, Uurl, Ssuccess);

                    //window.setTimeout("window.tryAgain", 1000);

                    alert("The server is being updated, please wait 5 seconds before submitting anything.");

                    //setTimeout("jax(" + jsondata + ", \"" + Uurl + "\", " + Ssuccess + ");", 1000);

                }
                else
                {
                    if (Uurl.toString().toLowerCase().indexOf("/login.asmx/ping") == -1)
                    {


                        $.ajax({
                            url: "/logerror.asmx/SaveErrors",
                            cache: false,
                            type: "POST",
                            data: { errorData: XMLHttpRequest.responseText, LocInfo: XMLHttpRequest.getAllResponseHeaders(), ErrorThrown: errorThrown, TextStatus: textStatus, request: getProperties(Ddata), url: Uurl },
                            success: function(msg) { eval($('string', msg).text()); },
                            error: function(XMLHttpRequest, textStatus, errorThrown) { alert(XMLHttpRequest.responseText) }
                        });
                    }
                }
            }

        }

    });
}

function getProperties(obj) {
  var i, v;
  var count = 0;
  var props = [];
  if (typeof(obj) === 'object') {
    for (i in obj) {
      v = obj[i];
      if (v !== undefined && typeof(v) !== 'function') {
        if (i != "undefined")
        {
           props[count] = i;
           count++;
        }
      }
    }
  }
  
  var allprops;
  for (i in props)
  {
    if (i != "undefined")
    {
        allprops += "\n\r" + props[i] + ": " + obj[props[i]];
    }
  } 
  
  return allprops;
};



function Ping()
{ 
    jax(null, "/login/login.asmx/Ping", function(msg) {eval( $('string',msg).text() );});
}


//to currency
function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.substring(0,num.length-(4*i+3))+','+
        num.substring(num.length-(4*i+3));
    return (((sign)?'':'-') + '$' + num + '.' + cents);
}

$().ready(function() {
    
    tips();
    $("input[@type=radio]").css({border:"none"});
    
}); 


function tips() {
$('.tip').Tooltip({
		track: true,
		delay: 0,
		showURL: false,
		showBody: " - "
    }); 
}

function bellows(topdog, headers)
        {
            $(topdog + " " + headers).unbind('click').css({'font-weight': 'normal'});
            $(topdog + " " + headers)
                .attr('showing', 'false')
                .click(function() {
                if ($(this).attr('showing') == 'false')
                { 
                    $(this).parent().siblings().children(headers).attr('showing', 'false')
                    $(this).attr('showing', 'true');
                    $(this).css({'font-weight': 'bold'})
                    $(this).next().slideDown('fast').css({'padding-left':'10px'}); 
                    $(this).parent().siblings().children(headers).css({'font-weight': 'normal'}).next().slideUp('fast'); 
                 }
                 else
                 { 
                    $(this).css({'font-weight': 'normal'}).next().slideUp('fast');
                     $(topdog + " " + headers).unbind('click');
                     bellows(topdog, headers); 
                }
            });
            $(topdog + " " + headers).next().hide(); 
            $(topdog).show();
         }
       
       
//scrolling
function f_clientWidth() {
	return f_filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}
function f_clientHeight() {
	return f_filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}
function f_scrollLeft() {
	return f_filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

function scrollPos()
{
	if ((f_scrollTop() + (f_clientHeight()/2) - 400 ) > 50)
	{
		return (f_scrollTop() + (f_clientHeight()/2) - 400 ) ;
	}
	else
	{
	return 50;
	}
}
 
function doScroll() {

		$("#Loading").css("top", f_scrollTop());
		 
		//alert(f_scrollTop());
}

window.onscroll = doScroll;

function LoadForm(holderdiv, cols, table, where, legend)
{
    $("#Loading").show();
    $("#" + holderdiv).children().remove(); 
    jax({cols: cols, table: table, where: where, holderdiv : holderdiv, legend  :legend}, "default.asmx/GetEditableForm", function(msg) {
        $("command string", msg).each(function() { eval($(this).text()); });  //execute 
        if ($("#" + holderdiv+ " .inputs").length == 0)
        {
             $("command string", msg).each(function() { eval($(this).text()); });  //execute
        }
        $("#" + holderdiv+ " .inputs").each(function() {
            var val = $(this).attr('value')
            if (val)
            {
                if (val.length == 0 || val == 'undefined')
                {       
                    $(this).show();   
                    $(this).attr('value','');
                } 
                else 
                {  
                    $(this).hide();   
                }   
            }
            else 
            {       
                $(this).show();   
            }  

    
            $("#" + holderdiv + " .datetime").attachDatepicker( {onSelect : function(datetext) { UpdateForm(this, table, where, holderdiv);} } );
            
            $("#" + holderdiv+ "  .formText, #" + holderdiv+ "  .datetimespan")
                .show()
                .click(function() {
                    $(this).hide();
                    $("#" + holderdiv + " #" + $(this).attr("id").substring(4) ).show().focus().click();
            });
              
            $("#" + holderdiv+ " input[@type=checkbox]").click(function() {
                $("#Loading").show();
                var clicked = this;
                $(clicked).hide(); 
                var col = $(clicked).attr('id');
                var newval;  
                if ($(clicked).attr('checked') == true)
                {   newval = 1; } 
                else {newval = 0;}
                jax({newvalue: newval, col : col, table: table, where: where}, "default.asmx/updateColumn", function(msg) {
                    if ($("string", msg).text() == "1")
                    {
                        
                        $(clicked).fadeIn('fast')
                        
                    } else { alert('field not updated, sorry.'); }
                    $("#Loading").fadeOut();
                    
                }); 
                
            });
            
            $("#" + holderdiv+ " .inputs:not(.datetime)").blur(function() {
               UpdateForm(this, table, where, holderdiv);
            }); 
                
            $("#" + holderdiv).show();
             
         });
         $("#Loading").fadeOut(); 
    });  
}

 

function UpdateForm(input, table, where, holderdiv)
{
    if ($(input).attr('value') ==  $("#" + holderdiv+ " #span" + $(input).attr("id")).text() &&  $(input).attr('value').length > 0  )
    {
        $(input).fadeOut('slow', function() {
            $("#" + holderdiv+ " #span" + $(input).attr("id") ).fadeIn('fast');
        });   
    }
    else
    {

        $("#Loading").show();
        var clicked = input;
        var col = $(clicked).attr('id');
        var newval = $(clicked).attr('value'); 
        jax({newvalue: newval, col : col, table: table, where: where}, "default.asmx/updateColumn", function(msg) {
            if ($("string", msg).text() == "1")
            {   
                $(clicked).fadeOut('fast', function() {
                    $("#" + holderdiv+ " #span" + $(clicked).attr("id") )
                        .fadeIn('fast')
                        .text($(clicked).attr('value')); 
                }); 
            } else { alert('field not updated, sorry.'); }
            $("#Loading").fadeOut();
            
        }); 
    }
}