﻿

///////////////////////////////////////
//          Constants               //
//////////////////////////////////////
var NullString = 'NULL';

// Messages
var Messages = new function(){};

Messages.ERROR = "An unexpected error accured.\n\r Detailes: {0}";

Messages.GetString = function(strString,args) {
    return String.Format( eval( 'Messages.' + strString ), ArrayFromArgs(arguments).slice(1));
}

window.onerror = Error;

//////////////////////////////////////////////////////////////////////////////////////////
//                          Ajax actions Class                                  
//////////////////////////////////////////////////////////////////////////////////////////
function AjaxManager ()
{
    /// <value type="function(String)"></value>
    this.OnError; 
    this._timeout = 40000; // 40 seconds time out
    this._xmlHttpRequest;
    this._timer = null;
    this._started = false;
    var _this = this;
    this._onError = function(e){
        _this.CancelRequest();
        if( _this.OnError )  _this.OnError(e);
        
        }
    this._onTimeout = function(){
        _this.CancelRequest();
        _this._onError('timeout');
        }
    this._clearTimeOut = function(){
            if (_this._timer != null) {
                window.clearTimeout(_this._timer);
                _this._timer = null;
            }
        }
    this._getXMLHTTPObject = function(){
           var ajaxObj = null; 
           try { ajaxObj = new ActiveXObject("Msxml2.XMLHTTP"); }
           catch(c) { try { ajaxObj = new ActiveXObject("Microsoft.XMLHTTP"); } 
              catch(b) {ajaxObj = null;} }
           if(!ajaxObj && typeof XMLHttpRequest != "undefined") {
              ajaxObj = new XMLHttpRequest;}
           return ajaxObj;
        }     
    this.CancelRequest = function() {
            if(_this._xmlHttpRequest && _this._started){
                _this._xmlHttpRequest.abort();
            }
	        _this._requestCompleted();
        }     
    this._get_httpVerb = function(data){
            if (data === null) {
                return "GET";
            }
            return "POST";
        }   
   this._requestCompleted = function(){
        _this._clearTimeOut();
        if (_this._xmlHttpRequest != null) {
                _this._xmlHttpRequest.onreadystatechange = Function.emptyMethod;
                _this._xmlHttpRequest = null;
            }
         _this._started = false;
        }
   // Cancel active xttpRequset on unload
   window.onunload = CombineHandlers(window.onunload,this.CancelRequest);
   
    /// <param name="serverUrl" type="String"></param>
    /// <param name="async" type="Boolen"></param>
    /// <param name="data" type="String"></param>
    /// <param name="callBackMethod" type="function(String)"></param>
    this.ExecuteRequest = function (serverUrl, async, data, callBackMethod ){
            if(this._xmlHttpRequest)
            {
                if(this._started || (this._xmlHttpRequest.readyState != 0 && this._xmlHttpRequest.readyState != 4))
                { this._xmlHttpRequest.abort(); }
            }
            this._xmlHttpRequest = this._getXMLHTTPObject();
            var _httpVerb = this._get_httpVerb(data);

            this._xmlHttpRequest.open( _httpVerb, serverUrl, async );
            this._xmlHttpRequest.setRequestHeader('PixeliT-Ajax', 'true');
            if (_httpVerb === "POST") {
                this._xmlHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                if (!data) {
                    data = "";
                }
            }
            else{
                 this._xmlHttpRequest.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
                 this._xmlHttpRequest.setRequestHeader("Cache-Control", "no-cache");
            }
            if( async ){
                this._xmlHttpRequest.onreadystatechange = function () {
                    if (_this._xmlHttpRequest.readyState == 4) {
                        try{
                        var _responseText = _this._xmlHttpRequest.responseText;
                        _this._requestCompleted();
                        if(  callBackMethod != null ){
                            callBackMethod(_responseText,  serverUrl);
                        } }catch(e){ _this._onError(e); };
                    }
                }
            }
            try{
             this._timer = window.setTimeout(Delegate(this, this._onTimeout), this._timeout);
             this._xmlHttpRequest.send(data);
             this._started = true;
             } catch(e){ _this._onError(e); };
             
            if( !async ){
                if( !_this._xmlHttpRequest ) return "";
                var _responseText = _this._xmlHttpRequest.responseText;
                _this._requestCompleted();
                return  _responseText;
            } 
        }
 }
 
 //////////////////////////////////////////////////////////////////////////////////////////
//                          Cache manager Class                                  
//////////////////////////////////////////////////////////////////////////////////////////
function CacheManager()
{
    this._cache = new Array();
    this.Insert = function ( key, value ){
        this._cache[key] = value;
        }
    this.Get = function ( key ){
        return this._cache[key];
        }
    this.Contains = function ( key ){
        return String.IsNullOrEmpty(this._cache[key]) ? false : true;
        }
}
 /////////////////////////////////////////////////////////////////////////////////////////
 
 // Ajax object
 var Ajax = new AjaxManager();
 Ajax.OnError = Error;
 // Cache object
 var Cache = new CacheManager();
 
  // Show error message
 function Error(err)
 {
    alert( Messages.GetString('ERROR',err) );
 }
 
 
 
////////////////////////////////////////////////////
//                 Helper methods                 //
////////////////////////////////////////////////////

//
//  Set element innerHTML, and execute the javascript code in it
//
function SetInnerHTML(elementId, text)
{
   var elm = $getElement(elementId)
   if( elm ){
       elm.innerHTML = text;
       var x = elm.getElementsByTagName("script"); 
       for(var i=0;i<x.length;i++)
       {
           eval(x[i].text);
       }
   }
}
//
//  Check if the client berowser is Fuc... Internet Explorer
//
function IsIE() {
    return navigator.userAgent.indexOf("MSIE") >= 0
}
//
//  Remove a given suffix from a string (if exist)
//
function RemoveSuffix(value,suffix)
{
    if(!String.IsNullOrEmpty(value) && value.EndsWith(suffix))
    {
        return value.substring(0,value.length-suffix.length);
    }
    return value;
}

//
//  Get the scroll offset top & left
//
function getScrollOffset() {
    var x, y;
    if(self.pageYOffset) {
        x = self.pageXOffset;
        y = self.pageYOffset;
    }
    else {
        if(document.documentElement && document.documentElement.scrollTop) {
            x = document.documentElement.scrollLeft;
            y = document.documentElement.scrollTop;
        }
        else {
            if(document.body) {
                x = document.body.scrollLeft;
                y = document.body.scrollTop;
            }
        }
    }
    return { left: parseInt(x), top: parseInt(y) };
 }
 
//
//  Get an element by Id
//
function $getElement (elementID){
     if( document.getElementById(elementID) )
         return document.getElementById(elementID);
     var reg = new RegExp(  elementID + "$" );
     var pageElements = document.getElementsByTagName("*");
     for(i = 0; i < pageElements.length; i++){
         elm = pageElements[i];
         if( elm.id ){
            if ( reg.test(elm.id) )   
                return elm;
         }
    }
    return null; 
}
//
// Get browser window width
//
function BrowserWidth(){
    if (window.innerWidth)
        return window.innerWidth;
    return document.body.clientWidth;
}
//
// Get browser window height
//
function BrowserHeight() {
    if (window.innerHeight)
        return window.innerHeight;
    return document.body.clientHeight;
}
//
// String.Format implementation
//
String.Format = function(format,args){
    var result = format;
    for(var i = 1 ; i < arguments.length ; i++) {
        result = result.replace(new RegExp( '\\{' + (i-1) + '\\}', 'g' ),arguments[i]);
    }
    return result;
} 
//
// string.EndsWith implementation
//
String.prototype.EndsWith = function(suffix,ignoreCase) {
    if( !suffix ) return false;
    if( suffix.length > this.length ) return false;
    if( ignoreCase ) {
        if( ignoreCase == true ) {
            return (this.substr(this.length - suffix.length).toUpperCase() == suffix.toUpperCase());
        }
    }
    return (this.substr(this.length - suffix.length) === suffix);
}
//
// string.StartWith implementation
//
String.prototype.StartsWith = function(prefix, ignoreCase) {
    if (!prefix) return false;
    if (prefix.length > this.length) return false;
    if (ignoreCase) {
        if (ignoreCase == true) {
            return (this.substr(0, prefix.length).toUpperCase() == prefix.toUpperCase());
        }
    }
    return (this.substr(0, prefix.length) === prefix);
} 
//
// string.Trim implementation
//
String.prototype.Trim = function() {
    return this.replace(/^\s+|\s+$/g, '');
} 
//
// String.IsNullOrEmpty implementation
//
String.IsNullOrEmpty = function(value){
    if(value){
        if( typeof( value ) == 'string' ){
             if( value.length > 0 )
                return false;
        }
       if( value != null )
           return false;
    }
    return true;
} 
//
// Create an array from the arguments
//
function ArrayFromArgs(args){
    var newArray = new Array();
    for (var i=0;i<args.length;i++)
        newArray[i] = args[i];
    return newArray;
}
//
//  Create a delegate to a method
//
function Delegate(instance, method) {
    return function() {
        return method.apply(instance, arguments);
    }
}
//
// Define an empty method
//
Function.emptyMethod = function() {
}
// Combine two handlers (Methods)
function CombineHandlers(origHandler, newHandler) {
	if (!origHandler || typeof(origHandler) == 'undefined') return newHandler;
	return function(e) { origHandler(e); newHandler(e); };
}

function Redirect(url) {
    location.href = url;
}

