﻿Type.registerNamespace("Core");

Core.MaxLengthBehavior = function(element) {
    Core.MaxLengthBehavior.initializeBase(this, [element]);

    this._maxLength = 0;
    this._output = null;
    this._emptyMessage = "";
    this._keyupHandler = null;
}
Core.MaxLengthBehavior.prototype =
{
    initialize: function() {
        Core.MaxLengthBehavior.callBaseMethod(this, 'initialize');
        this._keyupHandler = Function.createDelegate(this, this._onKeyup);
        $addHandler(this.get_element(), "keyup", this._keyupHandler);
        this._output = $get(this._output);
        this._displayOutput();
        if (this._emptyMessage !== "") {
            if (this.get_element().value == "") {
                this.get_element().value = this._emptyMessage;
            }
            $addHandler(this.get_element(), "focus", Function.createDelegate(this, this._onFocus));
            $addHandler(this.get_element(), "blur", Function.createDelegate(this, this._onBlur));

        }
    },

    dispose: function() {
        $clearHandlers(this.get_element());
        Core.MaxLengthBehavior.callBaseMethod(this, 'dispose');
    },

    _onFocus: function(e) {
       
        if (this.get_element().value == this._emptyMessage) {
            this.get_element().value = "";
            this._displayOutput();
        }
    },

    _onBlur: function(e) {
        this.get_element().value = this.get_element().value.trim();
        if (this.get_element().value.trim() == "") {
            this._displayOutput();
            this.get_element().value = this._emptyMessage;
        }
    },

    _onKeyup: function(e) {

        if (this.get_element().value.length > this._maxLength) {
            this.get_element().value = this.get_element().value.substring(0, this._maxLength);
        }
        this._displayOutput();
    },

    _displayOutput: function() {
        if (this._output) {
            Element.removeChildElements(this._output);
            this._output.appendChild(document.createTextNode((this._maxLength - this.get_element().value.length)));
        }
    }
}

Core.MaxLengthBehavior.registerClass('Core.MaxLengthBehavior', Sys.UI.Behavior);

function replaceQueryStringParam(url, paramName, paramValue)
{
  var pos = url.search(/\?/)
  if (pos==-1)
  {
    return url + '?' + paramName + '=' + paramValue;
  }
  
  var urlSplitter = url.split("?");
  var newUrl = urlSplitter[0] + "?";
  var params = urlSplitter[1];
  
	if (params.length > 0)
	{
	  var arr = params.split("&");
		for(i=0;i<arr.length;i++)
		{
		  var nameValuePair = arr[i].split("=");
		  if (nameValuePair[0].toLowerCase() != paramName.toLowerCase())
		  {
			  newUrl += nameValuePair[0] + "=" + nameValuePair[1] + "&";
		  }
  	}
	}	
  newUrl += paramName + '=' + paramValue;
  return newUrl;
}


function doLogin()
{
  var err = "";
  var email = $get("txtEmail");

  var password = $get("txtPassword");
  err += Validation.validateMandatory(email, "Email", "");
  err +=  Validation.validateMandatory(password, "Password", "");
  
  if(err!=""){ $get("loginError").innerHTML = err;$get("loginError").style.display = "";}
  else
  {
    $get("loginError").style.display = "none";   
  }
  var myServiceProxy = new WebServices();
  myServiceProxy.set_defaultSucceededCallback(onLoginSuccess);
  myServiceProxy.set_defaultFailedCallback(onLoginError);
  myServiceProxy.DoLogin(email.value, password.value);   
}

function onLoginSuccess(profile)
{
  if (g_action==1) { if (profile.Phone1=="") { window.location.href = g_redirect1; return;} }
   else if (g_action==2) { if (profile.Phone1=="") { window.location.href = g_redirect2; return;} }
   else if (g_action==3) { if (profile.Phone1=="") { window.location.href = g_redirect3; return;} }
   else if (g_action==4) { if (profile.Phone1=="") { window.location.href = g_redirect4; return;} }
   else if (g_action==5) { if (profile.Phone1=="" || profile.Address1=="" || profile.City=="" || profile.State=="" || profile.Zip=="") { window.location.href = g_redirect5; return;} }
   else if (g_action==6) { if(profile.Phone1=="") { window.location.href = g_redirect6; return;} }
   
   if ($find("sameAs"))
   {
     var inputs = $find("sameAs").get_inputs();
     
     inputs[0].source = profile.FirstName + ' ' + profile.LastName;
     inputs[1].source = profile.Company;     
     inputs[2].source = profile.EmailAddress;     
     inputs[3].source = profile.Phone1;     
     inputs[4].source = profile.PhoneTypeID1;     
     inputs[5].source = profile.Phone2;     
     inputs[6].source = profile.PhoneTypeID2;          
     inputs[7].source = profile.Fax;  
   }
  
	 $get("innerLogin").style.display = "none";
	 $get("innerPopupForm").style.display = "";
	 
	 $get(ClientIDs.Login).style.display = "none";
	 $get(ClientIDs.Logout).style.display = "";
	 $get(ClientIDs.MyAccount).style.display = "";

	 if(ClientIDs.PropertyAlerts) { $get(ClientIDs.PropertyAlerts).style.display = "none"; }
	 $get(ClientIDs.Greeting).style.display = "";
	 $get(ClientIDs.Greeting).innerHTML = "Hi " + profile.FirstName + " " + profile.LastName;
	 	 
	 $get("divEmail").innerHTML = profile.EmailAddress;
	 $get(ClientIDs.lblPhoneType1).innerHTML = profile.PhoneType1 + ":";
	 $get(ClientIDs.tdPhone1).innerHTML = profile.Phone1;

	 if (ClientIDs.tdName) { $get(ClientIDs.tdName).innerHTML = profile.FirstName + ' ' + profile.LastName;}

   if(ClientIDs.tdCompany && profile.Company!="")
   {
	   if (ClientIDs.trCompany) { $get(ClientIDs.trCompany).style.display = ""; }
	   $get(ClientIDs.tdCompany).innerHTML = profile.Company;
   }  	 
 
   if(ClientIDs.tdAddress1)
   {

	   $get(ClientIDs.tdAddress1).innerHTML = profile.Address1;  
   }  
   if(ClientIDs.trAddress2 && profile.Address2!="")
   {
	   $get(ClientIDs.trAddress2).style.display = "";
	   $get(ClientIDs.tdAddress2).innerHTML = profile.Address2;  
   }     
   if(ClientIDs.tdCityStateZip)
   {
	   $get(ClientIDs.tdCityStateZip).innerHTML = profile.City + ", " + profile.State + " " + profile.Zip;  
   }  
	 
	 if(profile.Phone2!="")
   {
	   if (ClientIDs.trPhone2) { $get(ClientIDs.trPhone2).style.display = ""; }
	   $get(ClientIDs.lblPhoneType2).innerHTML = profile.PhoneType2 + ":";
	   $get(ClientIDs.tdPhone2).innerHTML = profile.Phone2;   
   }
	 if(profile.Phone3!="")
   {
     if(ClientIDs.trPhone3) { $get(ClientIDs.trPhone3).style.display = "";}
	   if(ClientIDs.lblPhoneType3) { $get(ClientIDs.lblPhoneType3).innerHTML = profile.PhoneType3 + ":"; }
	   if(ClientIDs.tdPhone3) { $get(ClientIDs.tdPhone3).innerHTML = profile.Phone3; }
   }   
   
   if(ClientIDs.tdFax && profile.Fax!="")
   {
	   if(ClientIDs.trFax) { $get(ClientIDs.trFax).style.display = ""; }
	   $get(ClientIDs.tdFax).innerHTML = profile.Fax;  
   }  
	  	 	 	 
	 g_requiresLogin = false;
 
}

function onLoginError(ret)
{
  $get("loginError").innerHTML = ret.get_message();$get("loginError").style.display = "";
}

function SaveNodeStatus(nodeId, state, imgToFlip, inAnimationMode)
{
  if (inAnimationMode) return;
  var expanded = false;
  
  var image = $get(imgToFlip);
  if (image.src.indexOf("down.png") != -1)
  {
    image.src = image.src.replace("down.png","up.png");
   image.alt = "Collapse" 
    image.title = "Collapse" 
  }
	else
	{
	  image.src = image.src.replace("up.png","down.png");
    image.alt = "Expand" 
    image.title = "Expand" 

 
	} 
  
	//inverted logic because we are changing status before the animation starts
  if (state == "closed") expanded = true;
	var myServiceProxy = new UserSpecific();
  myServiceProxy.SaveNodeStatus(nodeId, expanded);
}

var Calculations =  
{
//todo
  /*linear/constant speed animation looks clunky because the animation starts and stops and so abruptly. The solution is to   
    adjust the //speed of the animation based on a sinusoidal curve rather than a line so that the transition looks smoother —     basically, it should //start slow and end slow and speed up in the middle. */
  SineCurve: function(percentage)
  {
    return (1 - Math.cos(percentage * Math.PI)) / 2;
  }

}


function popupWindow(Page, WindowName, width, height) 
{
  var w = window.open (Page, WindowName, 'height=' + height + ', width=' + width + ', scrollbars=1, resizable=1');

// Window1 = window.open("Popup.aspx?id=" + OpenerFieldName, "QueryBuilderAudit", "width=800,height=400,left=100,top=200");
  w.focus();
  return false;
}

function limitCharsInTextarea(textarea, maxLength, elDisplayCountStr)
  {
    var elDisplayCount = $get(elDisplayCountStr);
    Element.removeChildElements(elDisplayCount);
    if (textarea.value.length > maxLength) {
      textarea.value = textarea.value.substring(0, maxLength);
    }
    elDisplayCount.appendChild(document.createTextNode((maxLength - textarea.value.length)));
  }

Type.registerNamespace("Core");

Core.PopupFormEventArgs = function(sender) {

  Core.PopupFormEventArgs.initializeBase(this);
  this.sender = sender;
}

//=========================================================================================
// PopupForm
//=========================================================================================
Core.PopupForm = function(element) {
  Core.PopupForm.initializeBase(this, [element]);
		
		this._popupForm = element;
		this._cancelHandler = null;

}

Core.PopupForm.prototype = {

    initialize: function() {
        Core.PopupForm.callBaseMethod(this, 'initialize');

        this._cancelHandler = Function.createDelegate(this, this.hide);

    },


    addCustomHandler: function(handler) {
        this.get_events().addHandler("custom", handler);
    },

    removeCustomHandler: function(handler) {
        this.get_events().removeHandler("custom", handler);
    },

    _custom: function(sender) {
        //raise custom event here
        //http://asp.net/AJAX/Documentation/Live/tutorials/CustomClientEvents/default.aspx
        var h = this.get_events().getHandler("custom");
        if (h) h(this, new Core.PopupFormEventArgs(sender));
    },

    show: function(sender) {
        this._custom(sender);

        Utils.showCurtain("curtain", this._popupForm);
        this._popupForm.style.zIndex = 20;
        this._popupForm.style.display = "";

        var viewportSize = Utils.getViewportSize();
        var popupBounds = Sys.UI.DomElement.getBounds(this._popupForm);
        var scrollingPositon = Utils.getScrollingPosition();

        this._popupForm.style.left = Math.round((viewportSize.width - popupBounds.width) / 2) + 'px';
        this._popupForm.style.top = (Math.round((viewportSize.height - popupBounds.height) / 2) + scrollingPositon.y) + 'px';

        this._popupForm.style.visibility = "visible";

        var curtain = $get("curtain");
        if (curtain) $addHandler(curtain, "click", this._cancelHandler);
        for (i = 0; i < this._cancelButton.length; i++) { $addHandler(this._cancelButton[i], "click", this._cancelHandler); }
    },

    hide: function() {
                var curtain = $get("curtain");
        if (curtain) $removeHandler(curtain, "click", this._cancelHandler);
        for (i = 0; i < this._cancelButton.length; i++) { $removeHandler(this._cancelButton[i], "click", this._cancelHandler); }

        Utils.hideCurtain("curtain");
        this._popupForm.style.visibility = "hidden";
        this._popupForm.style.display = "none";
    },


    dispose: function() {

        Core.PopupForm.callBaseMethod(this, 'dispose');
    },

    get_cancelButton: function() {
        return this._cancelButton;
    },
    set_cancelButton: function(value) {
        this._cancelButton = value;
    }

}

Core.PopupForm.registerClass('Core.PopupForm', Sys.UI.Control, Sys.IDisposable);  

var Utils =
{
	isIE6: function()
	{
	  if(Sys.Browser.agent == Sys.Browser.InternetExplorer && parseInt(Sys.Browser.version) === 6) { return true;}
	  else { return false }; 
	},

  openPopup: function(page, windowName, width, height)
  {
    // Try to open a popup window
    var w = window.open(page, windowName, 'height=' + height + ', width=' + width + ', scrollbars=1, resizable=1');
		// if w is not null, set focus
    if (w) { w.focus(); }
    // w is null, load the popup in the main window
    else { window.location.href = page; }
    return false;
	},

	setOpacity: function(el, value)
	{
	  if (typeof el.style.opacity != 'undefined')
	  {
	    el.style.opacity = value;	 	  
	  }
	  else if (typeof el.style.MozOpacity != 'undefined')
	  {
	    el.style.MozOpacity = value;	  
	  }
	  else if (typeof el.style.KhtmlOpacity != 'undefined')	
	  {
	    el.style.KhtmlOpacity = value;
	  }
	  else if (typeof el.style.filter != 'undefined')	
		{
		  el.style.filter = "alpha(opacity=" + (value * 100) + ")";
		}
	},


  showCurtain: function(curtainEl, refEl)
  {
		//Hide Select Boxes (IE6 bugfix)
		if (Utils.isIE6())
		{
	    var s = document.getElementsByTagName("select");
	    for (i=0;i<s.length;i++) 
	    {
			  //But don't hide Select Boxes that have class="overideCurtain" in them
			  if (!Sys.UI.DomElement.containsCssClass(s[i], "overideCurtain"))
			   s[i].style.visibility = "hidden";
	    }  
		}

    var theBody = document.getElementsByTagName("body")[0];
		var theBodyBounds = Sys.UI.DomElement.getBounds(theBody);
		var pageSize = Utils.getPageSize();

	  var div = document.createElement("div");
	  div.id = curtainEl;
	  div.style.position = "absolute";

	  Utils.setOpacity(div,.55);

    //width for curtain: get from MS Ajax function .getBounds because Firefox includes scrollbar in calculation
    div.style.width = theBodyBounds.width + 'px';
    //For height we use pagesize function otherwise 20px will be missing in Firefox
	  div.style.height = pageSize[1] + 'px';
	  div.style.top = '0px';
	  div.style.left = '0px';
	  div.style.zIndex = 10;
	  div.style.backgroundColor = "#000"; //black

	  if (refEl)
	  {
	    refEl.parentNode.appendChild(div); //Firefox 2 hack
	  }
	  else
	  {
	    theBody.appendChild(div);
	  }
  },
  
  hideCurtain: function(curtainEl)
  {
  	if (Utils.isIE6())
	  {
	   	//Show Select Boxes again (IE6 bugfix)
	    var s = document.getElementsByTagName("select");
	    for (i=0;i<s.length;i++) {s[i].style.visibility = "visible";}
		}
		var divCurtain = $get(curtainEl);
		if (divCurtain != null)
		divCurtain.parentNode.removeChild(divCurtain);
  },
  
  getViewportSize: function()
  {
    var size = { width:0, height:0 };
    
    if (typeof window.innerWidth != 'undefined')
    {
      size.width = window.innerWidth;
      size.height = window.innerHeight;
    }      
		else if (typeof document.documentElement != 'undefined'
      && typeof document.documentElement.clientWidth != 'undefined'
      && document.documentElement.clientWidth != 0)
		{
      size.width = document.documentElement.clientWidth;
      size.height = document.documentElement.clientHeight;
    }
		else
		{
		  size.width =  document.getElementsByTagName('body')[0].clientWidth;
      size.height =  document.getElementsByTagName('body')[0].clientHeight;
		}
		return size;
  },
  
  getScrollingPosition: function()
	{
    var position = { x:0, y:0 };

    if (typeof window.pageYOffset != 'undefined')
    {
       position.x = window.pageXOffset;
       position.y = window.pageYOffset;
		}
    else if (typeof document.documentElement.scrollTop != 'undefined'
      && (document.documentElement.scrollTop > 0 ||
      document.documentElement.scrollLeft > 0))
    {
      position.x = document.documentElement.scrollLeft;
      position.y = document.documentElement.scrollTop;
    }
    else if (typeof document.body.scrollTop != 'undefined')
    {
      position.x = document.body.scrollLeft;
      position.y = document.body.scrollTop;
    }
    return position;
  },
  
    // =====================================================================================================
	// getPageSize()
  // =====================================================================================================
	// Returns array with page width, height and window width, height
	// Core code from - quirksmode.org
	// Edit for Firefox by pHaez
  getPageSize: function(){
	
		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;
		}

		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){	
			pageWidth = windowWidth;
		}	
		else { pageWidth = xScroll;}

		arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
		return arrayPageSize;
  }
	// -----------------------------------------------------------------------------------
  
  
}


var ToolTip =
{
  _toolTipID : "ToolTipWrapper",
  _cssClass: "toolTip",
  width : "auto",
  _htmlCache : null,
  
  showToolTip: function(sender, htmlId)
  {
 
    var div = document.createElement("div");
    div.id = ToolTip._toolTipID;
    div.style.width = ToolTip.width;
    div.style.position = "absolute";
    Sys.UI.DomElement.addCssClass(div, ToolTip._cssClass);

  	var senderBounds = Sys.UI.DomElement.getBounds($get(sender));
  
    div.style.top = senderBounds.y + 'px';
    div.style.left = (senderBounds.x + senderBounds.width + 5) + 'px';

		ToolTip._htmlCache = $get(htmlId)
		if (ToolTip._htmlCache)
		{
		  ToolTip._htmlCache.style.display = "";

			div.appendChild(ToolTip._htmlCache);
		
			document.getElementsByTagName("body")[0].appendChild(div);
		}
  },
  
  hideToolTip: function()
  {
		//Store tooltip content back in the body area and hide it.  
		if (ToolTip._htmlCache)
		{
		  ToolTip._htmlCache.style.display = "none";
		  document.getElementsByTagName("body")[0].appendChild(ToolTip._htmlCache);
		}
		//Remove the ToolTip Wrapper from the document
    var div = $get(ToolTip._toolTipID);
		if (div) div.parentNode.removeChild(div);
  }  
}


var StringFormatting = 
{
  formatCurrencyDollarNoPrecision: function(decimalToFormat)
  {
    return StringFormatting._formatCurrency(decimalToFormat, 0, true)
  },
  formatCurrencyDollar: function(decimalToFormat)
  {
    return StringFormatting._formatCurrency(decimalToFormat, 2, true)
  },

  formatDecimal: function(decimalToFormat)
  {
    return StringFormatting._formatCurrency(decimalToFormat, 2, false)
  },

  //Original:  Cyanide_7 (leo7278@hotmail.com)
  // Web Site:  http://www7.ewebcity.com/cyanide7 
  _formatCurrency: function(num, decimalPrecision, showCurrencySymbol) 
  {
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num)) num = "0";
    if(decimalPrecision==0) num = Math.round(num);
    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));
    
    var ret = ((sign)?'':'-') + '' + num; 
    if (showCurrencySymbol == true) ret = "$" + ret;
    if (decimalPrecision == 2) ret += '.' + cents;
    return ret;
  }


}

var Validation =
{
  validateMandatory: function(textField, textFieldName, defaultValue)
  {
    // Check if field is empty or has White Space only
    if (textField.value == "" || /^\s+$/.test(textField.value))
    {

      //If a default value was specified, assign it
      if(defaultValue != "") textField.value = defaultValue;
      //else return Error Message
      else return (textFieldName + " is a required field.<br/>");
    }  
    return "";
  },

  validateInteger: function(textField, textFieldName, defaultValue, minValue, maxValue)
  {
    // Check if field is empty or has White Space only
    if (textField.value == "" || /^\s+$/.test(textField.value))
    {

      //If a default value was specified, assign it
      if(defaultValue != "") textField.value = defaultValue;
      //else return Error Message
      else return (textFieldName + " is a required field.");
    }  
    //Check if input is of type Integer by comparing parsed string to source string, if different, input is not of type Integer
	if (textField.value + '' !==  parseInt(textField.value) + '')
	{
	  return "Input for " + textFieldName + " has to be of type Integer.";
	}
    if (typeof(minValue) != "undefined" && typeof(maxValue) != "undefined")
    {
      if (textField.value<minValue||textField.value>maxValue)
        return "Input for " + textFieldName + " has to be between "  + StringFormatting.formatCurrencyDollarNoPrecision(minValue) + " and " + StringFormatting.formatCurrencyDollarNoPrecision(maxValue) + "."; 
    }
    return "";

  },

  validateDecimal: function(textField, textFieldName, defaultValue, minValue, maxValue)
  {
    // Check if field is empty or has White Space only
    if (textField.value == "" || /^\s+$/.test(textField.value))
    {
      //If a default value was specified, assign it
      if(defaultValue != "") textField.value = defaultValue;
      //else return Error Message
      else return (textFieldName + " is a required field.");
    }  
    //Check if input is of type Integer by comparing parsed string to source string, if different, input is not of type Integer
	if (/^-?\d+(\.\d+)?$/.test(textField.value) == false)
	{
	  return "Input for " + textFieldName + " has to be of type Decimal.";
	}
    if (typeof(minValue) != "undefined" && typeof(maxValue) != "undefined")
    {
      if (textField.value<minValue||textField.value>maxValue)
        return "Input for " + textFieldName + " has to be between "  + (minValue) + "% and " + maxValue + "%."; 
    }
    return "";

  }

}

var Element =
{
  removeChildElements: function(obj)
  {
    if (obj)
	  {
	    while (obj.firstChild)
	    {
	      $clearHandlers(obj.firstChild);
	      obj.removeChild(obj.firstChild);
	    } 
    }
  }

}

var Exceptions = 
{
  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();
   
    // Display the error.    
    alert("Stack Trace: " +  stackTrace + "<br/>" +
        "Service Error: " + message + "<br/>" +
        "Status Code: " + statusCode + "<br/>" +
        "Exception Type: " + exceptionType + "<br/>" +
        "Timedout: " + timedout);
  }
}

var Spinner = 
{
  show: function(spinnerEl, el)
  {
		var elementBounds = Sys.UI.DomElement.getBounds(el);
  
    spinnerEl.style.top = elementBounds.y + 'px';
    spinnerEl.style.left = elementBounds.x + 'px';
    spinnerEl.style.width = elementBounds.width + 'px';
    spinnerEl.style.height = elementBounds.height + 'px';
    spinnerEl.style.display = "";
  },
  
	hide: function(spinnerEl)
	{
   spinnerEl.style.display = "none";	  
	}
}







//=========================================================================================
// Remodeling Estimator
//=========================================================================================
Core.RemodelingEstimator = function() {
  Core.RemodelingEstimator.initializeBase(this);
  this._items = null; 
  this._subTotal = null;
  this._miscellaneous = null;
  this._total = null;
}
Core.RemodelingEstimator.prototype = {
  initialize: function(){
    Core.RemodelingEstimator.callBaseMethod(this, 'initialize');
  },
    
  dispose: function()
  {
    for (i=0;i<this._items.length;i++)
    {
      $clearHandlers(this._items[i].unitPrice);
      $clearHandlers(this._items[i].qty);
    }
    Core.RemodelingEstimator.callBaseMethod(this, 'dispose');
  },
    
  setItems: function(items, subTotal, miscellaneous, total)
  {
    this._items = items;
    this._subTotal = subTotal;
    this._miscellaneous = miscellaneous;
    this._total = total;

    for (i=0;i<this._items.length;i++)
    {
      $addHandler(this._items[i].unitPrice, "change", Function.createDelegate(this, this._calculateRemodelingCosts));
      $addHandler(this._items[i].qty, "change", Function.createDelegate(this, this._calculateRemodelingCosts));
    }
    this._calculateRemodelingCosts();
  },
  
  clearQuantityFields: function()
  {
    if (confirm('Do you really want to clear all quantity fields?'))
    {  
      for (i=0;i<this._items.length;i++)
      {
        this._items[i].qty.value = "";
      }
    }
		this._calculateRemodelingCosts();
  },
  
  _calculateRemodelingCosts: function()
  {
    var subTotal = 0
    for (i=0;i<this._items.length;i++)
    {
      var itemTotal = this._items[i].unitPrice.value * this._items[i].qty.value;
      if (!isNaN(itemTotal))
      {
        subTotal += itemTotal
        Element.removeChildElements(this._items[i].cost);
        this._items[i].cost.appendChild(document.createTextNode(StringFormatting.formatDecimal(itemTotal))); 
      } 
    }
    Element.removeChildElements(this._subTotal);
    this._subTotal.appendChild(document.createTextNode(StringFormatting.formatDecimal(subTotal)));  

		var misc = subTotal * .1;
    Element.removeChildElements(this._miscellaneous);
    this._miscellaneous.appendChild(document.createTextNode(StringFormatting.formatDecimal(misc))); 

    Element.removeChildElements(this._total);
    this._total.appendChild(document.createTextNode(StringFormatting.formatDecimal(subTotal + misc))); 
        	
  }
}

Core.RemodelingEstimator.registerClass('Core.RemodelingEstimator', Sys.Component);

//=========================================================================================
// InvestmentSummary
//=========================================================================================
Core.InvestmentSummary = function(element) {
  Core.InvestmentSummary.initializeBase(this, [element]);
		
		this._investmentChart = null;
		this._investmentGraph1 = null;
		this._investmentGraph2 = null;		
		//this._btnRecalculate = null;
		this._spnMarketRent = null;
		this._spinnerDiv = null;
		
		this._purchasePrice = null;
		this._salesValue = null;
		this._txtMarketRent = null;
		this._dropMarketRent = null;
		this._rentIncrease = null;
		this._yearlyAppreciation = null;
		this._financingYears = null;		
		this._percentDown = null;
		this._percentApr = null;
		
		this._lnkPrintListing = null;
		this._lnkPrintListingHandler = null;
		
		this._imgToolTipGrossProceeds = null;
		this._imgToolTipMortgagePayment = null;
		this._imgToolTipMortgageBalance = null;		
}

Core.InvestmentSummary.prototype = {

	initialize: function(){
    Core.InvestmentSummary.callBaseMethod(this, 'initialize');
		this._investmentChart1 = $get("investmentChart1",this.element);
		this._investmentChart2 = $get("investmentChart2",this.element);
		this._investmentGraph1 = $get("investmentGraph1",this.element);
		this._investmentGraph2 = $get("investmentGraph2",this.element);		
		//this._btnRecalculate = $get("btnRecalculate",this.element);	
		this._txtMarketRent = $get("txtMarketRent",this.element);		
		this._spnMarketRent = $get("spnMarketRent",this.element);	
		this._spinnerDiv = $get("divSpin",this.element);			

		$addHandler(this._dropMarketRent, "change", Function.createDelegate(this, this._dropMarketRent_change));
		//$addHandler(this._btnRecalculate, "click", Function.createDelegate(this, this._btnRecalculate_click));
		$addHandler(this._purchasePrice, "change", Function.createDelegate(this, this._recalculate));
		$addHandler(this._salesValue, "change", Function.createDelegate(this, this._recalculate));		
		$addHandler(this._txtMarketRent, "change", Function.createDelegate(this, this._recalculate));		

		$addHandler(this._rentIncrease, "change", Function.createDelegate(this, this._recalculate));		
		$addHandler(this._yearlyAppreciation, "change", Function.createDelegate(this, this._recalculate));		
		$addHandler(this._financingYears, "change", Function.createDelegate(this, this._recalculate));		
		$addHandler(this._percentDown, "change", Function.createDelegate(this, this._recalculate));		
		$addHandler(this._percentApr, "change", Function.createDelegate(this, this._recalculate));		

		this._lnkPrintListing = $get("lnkPrintListing");
		if (this._lnkPrintListing)
		{
		  this._lnkPrintListingHandler = Function.createDelegate(this, this._printFlyer);
		  $addHandler(this._lnkPrintListing, "click", this._lnkPrintListingHandler);
		}		
  },

	_showToolTip: function(){
	  // imgToolTipWhatever: t + oolTipWhatever = toolTipWhatever
	  ToolTip.showToolTip(this.id,'t' + this.id.substring(4));return false;
	},

	preLoad: function(){
    this._handleDropDown();	
		this._onRetrievingInvestmentSummary();
	},

	_printFlyer: function()
	{
		var val = this._validate();
    if (val != "")
    {
      alert("Can not create flyer because the following\ninvestment parameters are missing/incorrect:\n" + val);
      return;
    }  			
	
	  var sb = new Sys.StringBuilder("PropertyDetails.aspx?media=print");
    sb.append("&PropertyID=" + g_propertyID); //PropertyID, pull from Global variable
    sb.append("&pp=" + this._purchasePrice.value); //Purchase Price
    sb.append("&pv=" + this._salesValue.value); //Property Value
    var marketRent = (this._dropMarketRent.value == -1) ? this._txtMarketRent.value : this._dropMarketRent.value;
    sb.append("&mr=" + marketRent); //Market Rent
    sb.append("&ri=" + this._rentIncrease.value); //Rent Increase
    sb.append("&ya=" + this._yearlyAppreciation.value); //Yearly Appreciation
    sb.append("&fy=" + this._financingYears.value); //Financing Years
    sb.append("&pd=" + this._percentDown.value); //Percent Down
    sb.append("&pa=" + this._percentApr.value); //Percent APR
  	Utils.openPopup(sb.toString(),'PropertyDetailsFlyer',1000,600);
	},

  _dropMarketRent_change: function()
  {
    this._handleDropDown();
    if (this._dropMarketRent.value != -1 || (this._dropMarketRent.value == -1 && this._txtMarketRent.value.trim() != ""))
		{ this._recalculate(); }
  },
  
  _handleDropDown: function()
  {
    if (this._dropMarketRent.value == -1)
    {
      this._txtMarketRent.style.display = "";
      this._spnMarketRent.style.display = "none";
    }
    else
    {
      this._txtMarketRent.style.display = "none";
      this._spnMarketRent.style.display = "";
      
      Element.removeChildElements(this._spnMarketRent);
      this._spnMarketRent.appendChild(document.createTextNode(this._dropMarketRent.value));

    }  
  },

  _recalculate: function()
  {
		this._onRetrievingInvestmentSummary();
		return false;
  },
  
  _validate: function()
  {
    var sb = ""
    var str = Validation.validateInteger(this._purchasePrice, "Purchase Price", "", 1, 100000000) 
    if (str!="") sb+= str + "\n";
    str = Validation.validateInteger(this._salesValue, "Estimated Property Value", "", 1, 100000000)
    if (str!="") sb+= str + "\n";
    if (this._dropMarketRent.value == -1)
    {
        str = Validation.validateInteger(this._txtMarketRent, "Market Rent", "", 1, 1000000)
      if (str!="") sb+= str + "\n";
    }
    str = Validation.validateDecimal(this._rentIncrease, "Rent Increase", "", 0, 100)
    if (str!="") sb+= str + "\n";
    str = Validation.validateDecimal(this._yearlyAppreciation, "Yearly Appreciation", "", 0, 100)
    if (str!="") sb+= str + "\n";
    str = Validation.validateDecimal(this._percentDown, "Financing Percent Down", "", 0, 100)
    if (str!="") sb+= str + "\n";
    str = Validation.validateDecimal(this._percentApr, "Financing Percent APR", "", 0, 30)
    if (str!="") sb+= str + "\n";
    return sb;
  },
  
  _onRetrievingInvestmentSummary: function()
  {
		var val = this._validate();
    if (val != "")
    {
      alert(val);
      return;
    }  		
 
    var handler = Function.createDelegate(this, this._onReceiveInvestmentSummary);  
    var myServiceProxy = new WebServices();
    myServiceProxy.set_defaultSucceededCallback(handler);
    myServiceProxy.set_defaultFailedCallback(Exceptions.FailedCallback);

    var marketRent = (this._dropMarketRent.value == -1) ? this._txtMarketRent.value : this._dropMarketRent.value;
        
    myServiceProxy.CreateInvestmentSummary(this._purchasePrice.value, this._salesValue.value, marketRent, this._rentIncrease.value,this._yearlyAppreciation.value,this._financingYears.value,this._percentDown.value,this._percentApr.value);   
    Spinner.show(this._spinnerDiv, $get("investmentSummaryWrapper"));
  },
  
  _onReceiveInvestmentSummary: function(investmentSummary)
  {
		//clear all ToolTipHandlers
		if(this._imgToolTipGrossProceeds) $clearHandlers(this._imgToolTipGrossProceeds);
		if(this._imgToolTipMortgagePayment) $clearHandlers(this._imgToolTipMortgagePayment);
		if(this._imgToolTipMortgageBalance) $clearHandlers(this._imgToolTipMortgageBalance);
		  
	  this._investmentGraph1.src = investmentSummary.GraphUrl1;
	  this._investmentGraph2.src = investmentSummary.GraphUrl2;
	  
	 	while (this._investmentChart1.hasChildNodes()) 
	 	{
  	  this._investmentChart1.removeChild(this._investmentChart1.firstChild);
  	}  		
  	var DOM = stringToDOM(investmentSummary.ChartHtml1);
  	this._investmentChart1.appendChild(DOM);

	 	while (this._investmentChart2.hasChildNodes()) 
	 	{
  	  this._investmentChart2.removeChild(this._investmentChart2.firstChild);
  	}  		
  	var DOM = stringToDOM(investmentSummary.ChartHtml2);
  	this._investmentChart2.appendChild(DOM);

		//ToolTips
		this._imgToolTipGrossProceeds = $get("imgToolTipGrossProceeds");
		$addHandler(this._imgToolTipGrossProceeds, "click", this._showToolTip);
		$addHandler(this._imgToolTipGrossProceeds, "mouseout", ToolTip.hideToolTip);
		this._imgToolTipMortgagePayment = $get("imgToolTipMortgagePayment");
		$addHandler(this._imgToolTipMortgagePayment, "click", this._showToolTip);
		$addHandler(this._imgToolTipMortgagePayment, "mouseout", ToolTip.hideToolTip);
		this._imgToolTipMortgageBalance = $get("imgToolTipMortgageBalance");
		$addHandler(this._imgToolTipMortgageBalance, "click", this._showToolTip);
		$addHandler(this._imgToolTipMortgageBalance, "mouseout", ToolTip.hideToolTip);
		this._imgToolTipMarketValue = $get("imgToolTipMarketValue");
		$addHandler(this._imgToolTipMarketValue, "click", this._showToolTip);
		$addHandler(this._imgToolTipMarketValue, "mouseout", ToolTip.hideToolTip);

  	setTimeout("Spinner.hide($get('divSpin'))",500);
    
	},
	
	dispose: function()
  {
		//clear all ToolTipHandlers
		if(this._imgToolTipGrossProceeds) $clearHandlers(this._imgToolTipGrossProceeds);
		if(this._imgToolTipMortgagePayment) $clearHandlers(this._imgToolTipMortgagePayment);
		if(this._imgToolTipMortgageBalance) $clearHandlers(this._imgToolTipMortgageBalance);
		
	  if (this._lnkPrintListing) $clearHandlers(this._lnkPrintListing); //in case one was assigned  
    this._cancelHandler = null;
    this._lnkPrintListingHandler = null; 
    $clearHandlers(this._dropMarketRent);
    //$clearHandlers(this._btnRecalculate);
    $clearHandlers(this._purchasePrice);
    $clearHandlers(this._salesValue);
    $clearHandlers(this._txtMarketRent);
    $clearHandlers(this._rentIncrease);
    $clearHandlers(this._yearlyAppreciation);
    $clearHandlers(this._financingYears);
    $clearHandlers(this._percentDown);
    $clearHandlers(this._percentApr);            

    Core.InvestmentSummary.callBaseMethod(this, 'dispose');
  },
    
  get_purchasePrice : function() {return this._purchasePrice;},
  set_purchasePrice : function(value) {this._purchasePrice = value;},
  get_salesValue : function() {return this._salesValue;},
  set_salesValue : function(value) {this._salesValue = value;},
  get_dropMarketRent : function(){return this._dropMarketRent;},
  set_dropMarketRent : function(value) {this._dropMarketRent = value;},  
  get_rentIncrease : function() { return this._rentIncrease; },
  set_rentIncrease : function(value) { this._rentIncrease = value; },    
  get_yearlyAppreciation : function() { return this._yearlyAppreciation; },
  set_yearlyAppreciation : function(value) { this._yearlyAppreciation = value; },      
  get_financingYears : function() { return this._financingYears; },
  set_financingYears : function(value) { this._financingYears = value; },      
  get_percentDown : function() {return this._percentDown;},
  set_percentDown : function(value) { this._percentDown = value;},      
  get_percentApr : function() { return this._percentApr; },
  set_percentApr : function(value) { this._percentApr = value; }
}

Core.InvestmentSummary.registerClass('Core.InvestmentSummary', Sys.UI.Control);



//=========================================================================================
// CountiesByState
//=========================================================================================
Core.CountiesByState = function() {
  Core.CountiesByState.initializeBase(this);
}
Core.CountiesByState.prototype = {
  initialize: function(){
    Core.CountiesByState.callBaseMethod(this, 'initialize');

    $addHandler(this._dropState, "change", Function.createDelegate(this, this._getCountiesByState));
    this._getCountiesByState();

  },
  
  get_dropState : function() {return this._dropState;},
  set_dropState : function(value) {this._dropState = value;},

  get_dropCounties : function() {return this._dropCounties;},
  set_dropCounties : function(value) {this._dropCounties = value;},

  get_countyId : function() {return this._countyId;},
  set_countyId : function(value) {this._countyId = value;},

  _getCountiesByState: function()
  {
    if (this._dropState.value == "" || this._dropState.value == 0) return;
    var handler = Function.createDelegate(this, this._onReceiveCounties);  
    var myServiceProxy = new WebServices();
    myServiceProxy.set_defaultSucceededCallback(handler);
    myServiceProxy.set_defaultFailedCallback(Exceptions.FailedCallback);
    myServiceProxy.GetCountiesByState(this._dropState.value);    
  },
  
  _onReceiveCounties: function(counties)
  {
	  this._dropCounties.options.length = 0;
	  this._dropCounties.options[0] = new Option('- Select County -',0);
    for (i=0;i<counties.length;i++)
		{
		  this._dropCounties.options[this._dropCounties.options.length] = new Option(counties[i].CountyName,counties[i].CountyID);
		}
		if (this._dropState.options[0].value == "") { this._dropState.remove(0); }
	
		if (this._countyId > 0)
		{
			for(i=0;i< this._dropCounties.length;i++)
			{
				if(this._dropCounties.options[i].value==this._countyId)
				{
					this._dropCounties.selectedIndex = i;
				}
			}
		  this._countyId = 0;
		}
  },
    
  dispose: function()
  {
    Core.CountiesByState.callBaseMethod(this, 'dispose');
  }
}

Core.CountiesByState.registerClass('Core.CountiesByState', Sys.Component, Sys.IDisposable);

//=========================================================================================
// Same As
//=========================================================================================
Core.SameAs = function() {
  Core.SameAs.initializeBase(this);
}
Core.SameAs.prototype = {

  get_inputs : function() {return this._inputs;},
  set_inputs : function(value) {this._inputs = value;},

  get_chkBox : function() {return this._chkBox;},
  set_chkBox : function(value) {this._chkBox = value;},

  initialize: function()
  {
    Core.SameAs.callBaseMethod(this, 'initialize');
    
    $addHandler(this._chkBox, "click", Function.createDelegate(this, this._handleCheckbox));
    this._handleCheckbox();
  },
  
  _handleCheckbox: function()
  {
    if (this._chkBox.checked) {this._addHandlers();}
    else {this._removeHandlers();}
  },
  
  _addHandlers: function()
  {
		for (i=0;i<this._inputs.length;i++)
    {
    // 	$addHandler(this._inputs[i].source, "change", Function.createDelegate(this._inputs[i], this._element_change));
     	this._inputs[i].dest.disabled = true;
      this._inputs[i].dest.value = this._inputs[i].source.value;
    }  
  },
  
  _removeHandlers: function()
  {
		for (i=0;i<this._inputs.length;i++)
    {
    // 	$clearHandlers(this._inputs[i].source);
     	this._inputs[i].dest.disabled = false;
    }    
  },
    
  _element_change: function()
  {
    this.dest.value = this.source;
  },
    
  dispose: function()
  {
		this._removeHandlers();
   	$clearHandlers(this._chkBox);
    Core.SameAs.callBaseMethod(this, 'dispose');
  }

}
Core.SameAs.registerClass('Core.SameAs', Sys.Component, Sys.IDisposable);



//=========================================================================================
// M2M
//=========================================================================================

Core.M2M = function(element) {
  Core.M2M.initializeBase(this, [element]);
		this._radNoAlerts = null;	
		this._radAllAlerts = null;	
		this._radCountyAlerts = null;
}

Core.M2M.prototype = {
  initialize: function(){
    Core.M2M.callBaseMethod(this, 'initialize');

		$addHandler(this._dropState, "change", Function.createDelegate(this, this._dropState_change));
		$addHandler(this._addButton, "click", Function.createDelegate(this, this._addButton_click));
		$addHandler(this._delButton, "click", Function.createDelegate(this, this._delButton_click));
		$addHandler(this._leftListbox, "dblclick", Function.createDelegate(this, this._addButton_click));
		$addHandler(this._rightListbox, "dblclick", Function.createDelegate(this, this._delButton_click));
		this._radNoAlerts = $get("radNoAlerts");	
		this._radAllAlerts = $get("radAllAlerts");	
		this._radCountyAlerts = $get("radCountyAlerts");	
		$addHandler(this._radNoAlerts, "click", Function.createDelegate(this, this._toggleRadioButton));	
		$addHandler(this._radAllAlerts, "click", Function.createDelegate(this, this._toggleRadioButton));	
		$addHandler(this._radCountyAlerts, "click", Function.createDelegate(this, this._toggleRadioButton));	
  },
  
  _toggleRadioButton: function()
  {
    if (this._radCountyAlerts.checked) { this._element.style.display = ""; }
    else { this._element.style.display = "none"; }
  },
  
  _getRadioButton: function()
  {
    if (this._radNoAlerts.checked) { return 0; }
    else if (this._radAllAlerts.checked) { return 1; }
    else { return 2;  }
  }, 
  
  _setRadioButton: function(value)
  { 
    if (value == 0) { this._radNoAlerts.checked = true; }
    else if (value == 1) { this._radAllAlerts.checked = true; }
    else { this._radCountyAlerts.checked = true;  }
    this._toggleRadioButton();
  },
  
  load: function(rbValue)
  {
		this._setRadioButton(rbValue);
    this._getCountiesByState();
  },
  
  _dropState_change: function()
  {
    this._getCountiesByState();
  },
  
  _getCountiesByState: function()
  {
    if (this._dropState.value == "") return;
    var handler = Function.createDelegate(this, this._onReceiveCounties);  
    var myServiceProxy = new WebServices();
    myServiceProxy.set_defaultSucceededCallback(handler);
    myServiceProxy.set_defaultFailedCallback(Exceptions.FailedCallback);
    myServiceProxy.GetCountiesByState(this._dropState.value);    
  },

  saveSelection: function()
  {
    var arr = new Array();
    for (i=0;i<this._rightListbox.options.length;i++)
    {
      arr[i] = this._rightListbox.options[i].value;
    }
    var handler = Function.createDelegate(this, this._onAfterSaveSelection);  
    var myServiceProxy = new WebServices();
    myServiceProxy.set_defaultSucceededCallback(handler);
    myServiceProxy.set_defaultFailedCallback(Exceptions.FailedCallback);
    myServiceProxy.SaveCountySelection(arr, this._dropState.value, this._getRadioButton());  
    Utils.showCurtain("curtain");
  },
  
  _onAfterSaveSelection: function(err)
  {
 	  setTimeout("Utils.hideCurtain('curtain');",500);
    if (err != '')
    {
      alert(err);
    }
    else
    {
      alert("Your selection was successfully saved.");
    }
  },
  
  _onReceiveCounties: function(counties)
  {
	  this._leftListbox.options.length = 0;
    for (i=0;i<counties.length;i++)
		{
		  this._leftListbox.options[this._leftListbox.options.length] = new Option(counties[i].CountyName,counties[i].CountyID);
		}
		if (this._dropState.options[0].value == "")
		{
			this._dropState.remove(0);
		}
  },

  _addButton_click : function() {
	  for(var i = 0; i < this._leftListbox.length; i++) 
	  {
		  if(this._leftListbox.options[i].selected) 
		  {
		    var existsOnRightSide = false;
		    var leftId = this._leftListbox.options[i].value;
		    for (j=0;j<this._rightListbox.length;j++)
		    {

		      if (leftId == this._rightListbox.options[j].value)
		      {
		        existsOnRightSide = true;
		        break;
		      }
		    }
		    if (existsOnRightSide == false)
				{
		      this._rightListbox.options[this._rightListbox.length] = new Option(this._leftListbox.options[i].text + ", " + this._dropState.value, this._leftListbox.options[i].value);
		    }
				else
				{
				  alert("You have already added " + this._leftListbox.options[i].text + ", " + this._dropState.value + " to your list of counties.");
				}
		  }
	  }
  },
  
  _delButton_click : function() 
  {
	  for(var i = this._rightListbox.length - 1; i >= 0 ; i--) 
	  {
		  if(this._rightListbox.options[i].selected) this._rightListbox.options[i] = null;
	  }
  },

  dispose: function()
  {
    Core.M2M.callBaseMethod(this, 'dispose');
  },
    
  get_dropState : function() {return this._dropState;},
  set_dropState : function(value) {this._dropState = value;},

  get_leftListbox : function() {return this._leftListbox;},
  set_leftListbox : function(value) {this._leftListbox = value;},

  get_rightListbox : function() {return this._rightListbox;},
  set_rightListbox : function(value) {this._rightListbox = value;},

  get_addButton : function() {return this._addButton;},
  set_addButton : function(value) {this._addButton = value;},

  get_delButton : function() {return this._delButton;},
  set_delButton : function(value) {this._delButton = value;}  
 
  
}

Core.M2M.registerClass('Core.M2M', Sys.UI.Control);

Core.KeepSessionAlive = function() {
  Core.KeepSessionAlive.initializeBase(this);
  this._timer = null;
  // EventHandlers
  this._tickHandler = null;
}
Core.KeepSessionAlive.prototype = {
  initialize: function(){
    Core.KeepSessionAlive.callBaseMethod(this, 'initialize');

    this._tickHandler = Function.createDelegate(this, this._keepSessionAlive);
    this._timer = new Core.Timer();
    this._timer._interval = 600000; //Do this every 10 minutes
    this._timer.addTickHandler(this._tickHandler);
    this._timer.startTimer();
  },
    
  dispose: function()
  {
    if (this._timer) 
    {        
      this._timer.dispose();
      this._timer = null;
    }
    this._tickHandler = null;
    Core.KeepSessionAlive.callBaseMethod(this, 'dispose');
  },
    
  _keepSessionAlive: function()
  {
    Sys.Debug.trace("KeepSessionAlive");
    var myServiceProxy = new Core.Utils.KeepSessionAlive();
    myServiceProxy.Request();  
  }
}

Core.KeepSessionAlive.registerClass('Core.KeepSessionAlive', Sys.Component, Sys.IDisposable);

Core.Timer = function() 
{
    Core.Timer.initializeBase(this);
    this._interval = 1000;
    this._timer = null;
    this._enabled = false;
}

Core.Timer.prototype = {

    addTickHandler: function(handler)
    {
      this.get_events().addHandler("tick", handler);
    },
  
    _timerTick: function() {
        //raise custom event here
        //http://asp.net/AJAX/Documentation/Live/tutorials/CustomClientEvents/default.aspx
        var h = this.get_events().getHandler("tick");
        if (h) h(this, Sys.EventArgs.Empty);
    },

    startTimer: function() {
      if (this._enabled == false)
      {
        this._enabled = true;
        this._timer = window.setInterval(Function.createDelegate(this, this._timerTick), this._interval);
      }
    },

    stopTimer: function() {
        window.clearInterval(this._timer);
        this._enabled = false;
        this._timer = null;
    },
    
    dispose: function()
    {
      this.stopTimer();    
      Core.Timer.callBaseMethod(this, 'dispose');
    }

}

Core.Timer.registerClass('Core.Timer', Sys.Component, Sys.IDisposable);


Core.DivSlider = function(div, duration, savedState) {
    this._div = $get(div);
    if (!this._div) {return;}
    this._duration = duration;
    this._state = "open";
    if (typeof savedState != "undefined")
    {
      this._state = savedState;
    }
    if (this._state == "closed")
    { 
      this._div.style.display = "none";
    }
    else
    {
      this._div.style.display = "";    
    }
    this._div.style.overflow = "hidden";
    this._direction = null;
    this._startTime = null;
    this._divHeight = 0;
    this._inAnimationMode = false;
}

Core.DivSlider.prototype = {

  init: function()
  {
    if (this._state == "open") 
    {
      this._div.style.display = "";
    }
    this._div.style.height = "auto";
    
    var display = this._div.style.display; 
    if (display == "none")
    {
      this._div.style.display = ""; 
      this._divHeight = this._div.offsetHeight; 
      this._div.style.display = "none"; 
    }
    else
    {
      this._divHeight = this._div.offsetHeight; 
    }
  },
  
  execute: function() 
  {
    if (this._inAnimationMode == false)
    {
      this._inAnimationMode = true;
      this._div.style.display = "";
      this._startTime = new Date().getTime();
      this.init();
      this._animationLoop();
    }
  },  
    
  _animationLoop: function() 
  {
    var _this = this;
    var elapsedTime = new Date().getTime() - this._startTime;

    if (elapsedTime < this._duration)
    {
       
      var p = Calculations.SineCurve( elapsedTime / this._duration );
      if (this._state == "open") 
      {
        p = 1 - p;
      }
      this._div.style.height = (p * this._divHeight) + "px";
    //  this._div.style.opacity = p;
    //  this._div.style.MozOpacity = p;
    // this._div.style.filter = "alpha(opacity=" + (p * 100) + ")";
     // this._div.style.filter="progid:DXImageTransform.Microsoft.Alpha(opacity=" + (p * 100) + ");";

    
    
      setTimeout(function(){_this._animationLoop()}, 10);
    }
    else
    {
      this._div.style.height = (this._divHeight) + "px";
     // this._div.style.opacity = 1;
     // this._div.style.MozOpacity = 1;
     // this._div.style.removeAttribute('filter')// "alpha(opacity=100)";  
      this._inAnimationMode = false;
          
      if (this._state == "closed")    
      {
        this._state = "open";
      }
      else
      {
        this._div.style.display = "none";
        this._state = "closed";  
      }
    }  
  }

}

Core.DivSlider.registerClass('Core.DivSlider', null, Sys.IDisposable);
