﻿function TWOControl(windowElement) {
  this.element = windowElement;
  this._service=new Array();
  
  this._locktimeoutid;
  
  this.get_element = function() {
      return this.element;
  }
  
  this.set_DataSource = function(value, saveToBrowser) 
  {
      this._DataSource = value;
      try
      {
        if(saveToBrowser == true)
        {
            $.jStorage.set(this.get_element().id, value);
        }
      }
      catch(e)
      {
        //we may have cookies disabled? or we havent done something properly... ignore and behave as usual...
      }
  }
  
  this.get_DataSource = function() 
  {
        if(this._DataSource == undefined || this._DataSource == null)
        {
            var cachedVal = $.jStorage.get(this.get_element().id, null);
            if(cachedVal != null) 
            {
                this.set_DataSource(cachedVal);
            }
        }
        return this._DataSource;
  }

  this._findcontrol = function(name, context) {
      if(context == undefined || context == null) context = this.get_element();
      var control = $(context).find("#" + name)[0];
      if(control == undefined || control == null) control = this._findASPNETcontrol(name, context);
      return control;
  }

  this._findjcontrol = function(name, context) {
      if(context == undefined || context == null) context = this.get_element();
      var control = $($(context).find("#" + name)[0]);
      if(control[0] == undefined) control =this._findASPNETjcontrol(name, context);
      return control;
  }


  this._findASPNETcontrol = function(name, context) {
      if(context == undefined || context == null) context = this.get_element();
      return $(context).find("*[id*=" + name + "]")[0];
  }

  this._findASPNETjcontrol = function(name, context) {
      if(context == undefined || context == null) context = this.get_element();
      return $($(context).find("*[id*=" + name + "]")[0]);
  }

  this.hide = function() {
      $(this.get_element()).hide();
  }

  this.show = function() {
    $(this.get_element()).show();
  }

  this.GetCurrentHierarchy=function(value) { return _CurrentHierarchy; };
  this.SetCurrentHierarchy=function(value) { _CurrentHierarchy=value; };

  this.get_Service = function(name) {
    if(!name) name='default';
    return this._service[name];
  }
  this.set_Service = function(name, value) {
    if(!value) { value=name; name='default'; } 
    this._service[name] = value;
    this._service[name].set_defaultFailedCallback(this._FailedCallback);
  }    

  this.Lock = function(delay) {
    // TODO: set a timeout... so that it won't load until a few seconds...
    var myself=this;
    if(delay) {
      this._locktimeoutid=setTimeout(function() { myself.Lock(); }, delay);
    } else {
      $(this.get_element()).loading({ align: 'center', text: 'Loading...', mask: true, effect:'ellipsis update' });
    }
  }
  
this.LockjControl = function(jcontrol) 
{
    jcontrol.loading({ align: 'center', text: 'Loading...', mask: true, effect:'ellipsis update' });
}

this.UnLockjControl = function(jcontrol) {    
    jcontrol.loading(false);
  }

  this.UnLock = function() {
    clearTimeout(this._locktimeoutid);
    $(this.get_element()).loading(false);
  }

  this.LockControl = function(jItem) {
    jItem.loading({ align: 'center', text: 'Loading...', mask: true, effect:'ellipsis update' });
  }
  
  this.UnLockControl = function(jItem) {
    jItem.loading(false);
  }
  
  this._ResetEditor = function(jControl) {
    jControl.find(":input[type=text]").val("");
    jControl.find(":input[type=textarea]").val("");    
    jControl.find(":checkbox").attr('checked', false);
    jControl.find("select option[value='0']").attr('selected', 'selected');
  }
  
  this._BindElement = function(elementid, value, context) {
    var myself = this;
    if(!context) context = myself.get_element();
    var control = myself._findjcontrol(elementid, context);
    control.val(myself.ReplaceNullWithEmptyString(value));
    return control;
  }

  this.GetElementValue = function(elementid) {
      var myself = this;
      return myself._findjcontrol(elementid).val();
  }
  
  this.ReplaceNullWithEmptyString = function(value) {
      if(value == null) value = "";
      return value;
  }
  
  this.Alert = function(stitle, message) {
    var myself = this;
        	
    if(window.alertDiv == undefined) {
    	window.alertDiv = $("<div></div>");
    	window.alertDiv.dialog({
            modal: true,
            autoOpen: false,
            title: stitle,
            buttons: {
                Ok: function() {
                    $(this).dialog('close');
	            }
            }
        });
    }
    
    window.alertDiv.dialog('option','title', stitle);
    
    if(!window.alertDiv.dialog('isOpen')) {
	    window.alertDiv.dialog('open');
	    window.alertDiv.html(message);
    } else {
        window.alertDiv.html(window.alertDiv.html() + "<br /><br />" + message);
    }
  }
  
  this.Confirm = function(stitle, message, okbtntext, cancelbtntext, callback) {
      var myself = this;
      var btns = {};
      btns[okbtntext] = function(){ $(this).dialog('close').remove(); callback(); };
      btns[cancelbtntext] = function(){ $(this).dialog('close').remove(); };
	$("<div></div>").html(message).dialog({
		modal: true,
		title: stitle,
		buttons: btns
	});
  }
  
  this._FailedCallback = function(error) {

      var stackTrace = error.get_stackTrace();
      var message = error.get_message();
      var statusCode = error.get_statusCode();
      var exceptionType = error.get_exceptionType();
      var timedout = error.get_timedOut();
      
      $("<div></div>").html("Service Error: " + message + "<br/>" +
        "Status Code: " + statusCode + "<br/>" +
        "Exception Type: " + exceptionType + "<br/>" +
        "Timedout: " + timedout + "<br/>" +
        "Stack Trace: " +  stackTrace).dialog({
	    modal: true,
	    title: 'ERROR!',
	    buttons: {
		    Ok: function() {
			    $(this).dialog('close').remove();					
		    }
	    }
    });
  }
  
    this.DropDownContainsText = function(dropdown, text)
    {
        var myself = this;
        var contains = false;
        var dd = myself._findcontrol(dropdown);
        for (var ctr = 0; ctr < dd.options.length; ctr++)
        {
            if(dd.options[ctr].text == text)
            {
                contains = true;
                break;
            }
        }
        return contains;
    }
    
    /*
    If window address has MID= in it (querystring) get the merchant from cache, otherwise get from remote service call and set window.CurrentMerchant to that value... 
    */
    this.AddMerchant = function(merchant)
    {
        var myself = this;
        //check against cache again to make sure that another browser instance hasnt already inserted (additional step to attempt having no unnecessary duplicates).
        if(myself._GetFromCache(merchant.MID) == null)
        {
            var merchants = $.jStorage.get('Cached Merchants');
            merchants.splice(0, 0, merchant);//add merchant to top! of list
            $.jStorage.set('Cached Merchants', merchants);
        }
    }
    
    this._GetFromCache = function(MID)
    {
        var merchants = $.jStorage.get('Cached Merchants', null);
        var merchant = null;
        if(merchants != null)
        {
            for (var ctr = 0; ctr < merchants.length; ctr++) 
            {
                if(merchants[ctr].Mid == MID)
                {
                    merchant = merchants[ctr];
                    break;
                }
            }
        }
        else $.jStorage.set('Cached Merchants', new Array());
        return merchant;
    }
    
    this.GetMerchant = function(MID, success, failure)
    {
        var myself = this;
        if(typeof success != 'function') throw "Method requires a callback to invoke when merchant loaded.";
        
        //STEP 1 look in client cache
        var merchant = myself._GetFromCache(MID);
        if(merchant != null)
        {
            success(merchant);
        }
        else
        {
            //STEP 2 if not in client cache, get from server.
            Portal.MerchantService.GetMerchantByMerchantID(MID,
                function(result)
                {
                    merchant = result;
                    myself.AddMerchant(merchant);
                    success(merchant)
                },
                function(err)
                {
                    if(typeof failure != 'function')
                    {
                        myself._FailedCallback(err);
                    }
                    else failure(err);
                }
            );
        }
    }
    
    this.GetCurrentMerchant = function(callback, failedCallback)
    {
        var myself = this;
        if(typeof callback != 'function') throw "Expecting callback to invoke upon merchant load";
        var mid = getQuerystring("mid");//invoke function defined in global
        if(mid != "")
        {
            myself.GetMerchant(mid,
                function(merchant)
                {
	          if(merchant == null) {
                if(typeof failedCallback != 'function') {
                    myself.Alert('Error', 'Merchant not found.');
                }                  
		        else {
                    failedCallback();
                }
              } else {
                callback(merchant);
              }
            }
          );
        }
        else {
          callback(null);
        }
    }
}
