﻿var ClientIDs = {};

//Original:  Cyanide_7 (leo7278@hotmail.com)
// Web Site:  http://www7.ewebcity.com/cyanide7 

// This script and many more are available free online at 
// The JavaScript Source!! http://javascript.internet.com 
function formatCurrency(num, showDecimals) {
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));

var ret = ((sign)?'':'-') + '' + num
if (showDecimals) ret += '.' + cents;
return ret;
}

function loginPopup_show()
{
  var popup = $get("loginPopup");
  var navBarBounds = Sys.UI.DomElement.getBounds($get("mainmenu"));

  popup.style.display="block";
  popup.style.top = (navBarBounds.y + navBarBounds.height) + 'px'

  var popupBounds = Sys.UI.DomElement.getBounds(popup);

  popup.style.left = (navBarBounds.x + navBarBounds.width - Sys.UI.DomElement.getBounds(popup).width) + 'px'
  popup.style.visibility="visible";

  Sys.UI.DomEvent.addHandler($get("ctl00_Menu1_LoginPopup1_txtPassword"), "keydown", loginPopup_onKeyDown);
  $get("ctl00_Menu1_LoginPopup1_txtUserName").focus();
}


function loginPopup_hide()
{
  var popup = $get("loginPopup");
  popup.style.visibility="hidden";
  popup.style.display="none";
}

function loginPopup_onKeyDown(e)
{
  var k = e.keyCode ? e.keyCode : e.rawEvent.keyCode;
	if (k === Sys.UI.Key.enter)
	{
	  e.stopPropagation(); //Prevents an event from being propagated to parent elements. MS AJAX
    e.preventDefault();
    __doPostBack('ctl00$Menu1$LoginPopup1$btnSignin','')
    return false;
	}
}

function check(e){
 
//alert(e.target)
//var target = (e && e.target) || (event && event.srcElement); 
//alert(target)

//var obj = document.getElementById('negotiator'); 

var clickedAnchor = $get(myclickedAnchor); 

var removeHandler = false;

if (checkParent(e.target, popupDivNode) == true)
{
  popupDivNode.style.display='none';
  removeHandler = true;
} 
if (e.target==clickedAnchor)
{
  popupDivNode.style.display='block';
  removeHandler = false;   
}
if (removeHandler) 
{
$removeHandler(document, "click", check);
 Utils.hideCurtain("curtain");
 }
 //
} 

function checkParent(t, popupDiv){ 
while(t.parentNode){ 
if(t==popupDiv){ 
return false 
} 
t=t.parentNode 
} 
return true 
} 

var myclickedAnchor = null;
var popupDivNode = null;

function negotiator_show(id, clickedAnchor, currentOffer)
{
	Utils.showCurtain("curtain");
  popupDivNode = $get("negotiator")
  popupDivNode.style.zIndex = 1000;
  
   popupDivNode.style.display="block";
  var popupBounds = Sys.UI.DomElement.getBounds(popupDivNode);
  var theBodyBounds = Sys.UI.DomElement.getBounds($get("theBody"));

myclickedAnchor = clickedAnchor;

 popupDivNode.style.left = Math.round((theBodyBounds.width - popupBounds.width) / 2) + 'px';
 popupDivNode.style.top = Math.round((theBodyBounds.height - popupBounds.height) / 2) + 'px';

	$get("negotiatorOfferId").value = id;
	$get("currentOffer").innerHTML = "$" + formatCurrency(currentOffer, false)
//  popup.style.top = (navBarBounds.y + navBarBounds.height) + 'px'



//  popup.style.left = (navBarBounds.x + navBarBounds.width - Sys.UI.DomElement.getBounds(popup).width) + 'px'
  popupDivNode.style.visibility="visible";
$addHandler(document, "click", check);

}

function negotiator_hide()
{
	Utils.hideCurtain("curtain");
  var popup = $get("negotiator");
  popup.style.visibility="hidden";
  popup.style.display="none";
}



function calculateSavings()
{
  var salesPrice = $get("salesPrice");
  var valParsed = parseFloat(salesPrice.value.replace(",",""));
  
  salesPrice.value = valParsed;
  $get("calculatedCommissions").innerHTML = Math.round(valParsed * 0.06);
}


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;
}

// =============================================================================================================
// BEGIN Swap Images in Menu
// =============================================================================================================
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
// =============================================================================================================
// END Swap Images in Menu
// =============================================================================================================

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);  

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);
    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);



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);





// Notify ScriptManager that this is the end of the script.
if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

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;
  }

}




var Utils =
{
  showCurtain: function(curtainEl)
  {
		//Hide Select Boxes (IE6 bugfix)
	  var s = document.getElementsByTagName("select");
	  for (i=0;i<s.length;i++) {s[i].style.visibility = "hidden";}  

    var theBody = document.getElementsByTagName("body")[0];
		var theBodyBounds = Sys.UI.DomElement.getBounds(theBody);

	  var div = document.createElement("div");
	  div.id = curtainEl;
	  div.style.position = "absolute";
	  div.style.opacity = .55;
	  div.style.filter = "alpha(opacity=55)";
	  
//-moz-opacity: 0.55; -khtml-opacity: 0.55; }
		var pageSize = Utils.getPageSize();

	 // div.style.width = theBodyBounds.width + 'px';
	//  div.style.height = theBodyBounds.height + 'px';

  div.style.width = pageSize[0] + 'px';
	  div.style.height = pageSize[1] + 'px';


	  div.style.top = '0px';
	  div.style.left = '0px';
	  div.style.zIndex = '500';
	  div.style.backgroundColor = "#000";

		theBody.appendChild(div);

  },
  
  hideCurtain: function(curtainEl)
  {
		//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);
 
  },
  
  // -----------------------------------------------------------------------------------

// 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;
},

  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;
  }
  
    // =====================================================================================================
	//
  
// -----------------------------------------------------------------------------------
  
  
}

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);
}

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)));
  }

//if (field.value.length > maxlen) {
//field.value = field.value.substring(0, maxlen);
//alert('your input has been truncated!');
var Element =
{
  removeChildElements: function(obj)
  {
    if (obj)
	  {
	    while (obj.firstChild)
	    {
	      $clearHandlers(obj.firstChild);
	      obj.removeChild(obj.firstChild);
	    } 
    }
  }

}

