/*
  all the stuff that happens straight after page load
  ----------------------------------------------------
*/

Event.observe(window, 'load', function() {
  moveLinkHigher(".headerbox",".more");
  moveLinkHigher(".link-out",".link-inner");
  if(navigator.appName.indexOf("Netscape")>-1){
    wordWrapJS();
  };
	Event.observe(document, 'mousemove',quickQuoteExitSurvey);
});

function quickQuoteExitSurvey(event){
	var pageScroll = getPageScroll();
	if (getCookie('STARTED_QUOTE') && getCookie('STARTED_QUOTE')==1 &&event.pointerY() < pageScroll[1] + 10 ){
		setCookie("STARTED_QUOTE", 0, '');
		$('quote_abandonment_survey').show();
	}
}

function getCookie(key) {
 	var keyEquals = key+"=";
  var value = false;
  document.cookie.split(';').invoke('strip').each(function(s){
    if (s.startsWith(keyEquals)) {
        value = unescape(s.substring(keyEquals.length, s.length));
        throw $break;
    }
  });
  return value;
}

function setCookie (key, value, days) {
	 this.path = '/';
	 this.domain = null;
   if (typeof key != 'string') {
       throw "Invalid key";
   }
   if (typeof value != 'string' && typeof value != 'number') {
       throw "Invalid value";
   }
   if (days && typeof days != 'number') {
       throw "Invalid expiration time";
   }
   var setValue = key+'='+escape(new String(value));
   if (days) {
       var date = new Date();
       date.setTime(date.getTime()+(days*24*60*60*1000));
       var setExpiration = "; expires="+date.toGMTString();
   } else var setExpiration = "";
   var setPath = '; path='+escape(this.path);
   var setDomain = (this.domain) ? '; domain='+escape(this.domain) : '';
   var cookieString = setValue+setExpiration+setPath+setDomain;
   document.cookie = cookieString;
};


function getPageScroll(){
  var yScroll;

  if (self.pageYOffset) {
    yScroll = self.pageYOffset;
  } else if (document.documentElement && document.documentElement.scrollTop){  // Explorer 6 Strict
    yScroll = document.documentElement.scrollTop;
  } else if (document.body) {// all other Explorers
    yScroll = document.body.scrollTop;
  }
  
  arrayPageScroll = new Array('',yScroll) 
  return arrayPageScroll;
}


//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){
  
  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;
}




// display a message to the user
function display_notification(message) {
  var arrayPageSize = getPageSize();
  var arrayPageScroll = getPageScroll();
  // center lightbox and make sure that the top and left values are not negative
  // and the image placed outside the viewport
  var lightboxTop = 150 + arrayPageScroll[1];
  var lightboxLeft = ((arrayPageSize[0] - $('flash_msg_notice').getWidth()) / 2);
  
  $('flash_msg_notice').style.top = (lightboxTop < 0) ? "0px" : lightboxTop + "px";
  $('flash_msg_notice').style.left = (lightboxLeft < 0) ? "0px" : lightboxLeft + "px";

  $('flash-notice').innerHTML = message;
	
	// hack for white label being in an iframe screws up positioning
	if ($('create_lead_next')){
		var pos = getElementAbsolutePos($('create_lead_next'));
		$('flash_msg_notice').style.top = pos.y + -300 + "px";
	}
  $('flash-notice-std').show();
  $('flash_msg_notice').show();
}


// is the current user logged in?
function logged_in() {
  return _member.logged_in;
}

function request_login(do_after) {
  pop_over($('login-form'));
  // need to kill the existing on_submit stuff somehow
  // and rebuild with the do_after function
  ajaxOnSubmitEvent('login_form', '/login.json', login_form_onSubmit, function(t) { login_form_onSuccess(t, do_after) }, login_form_onFailure);
}

function login_form_onSubmit() {
  // hide the failed notice (if this is their second attempt)
  $('login-failed-notice').hide();
}
function login_form_onSuccess(t, do_after) {
  var result = t.responseJSON;
  
  // check if form submitted with empty form fields
 	if(result == null){
 		login_form_onFailure(t); 
 	}
 
  if (result.success) {
    _member.logged_in = true;
    close_pop_over();
    // need to set the original event running again
    do_after();
  } else {
  	
    // figure out what happened
    if (result.error == 'termsneeded') {
      display_notification('You need to accept the Terms and conditions before you can start using cmypitch.com');
      $('login-terms').show();
    }
    else {
      login_form_onFailure(t);      
    }
  }
}
function login_form_onFailure(t) {
  $('login-failed-notice').show();
}

// displays the given element in a popover shell
function pop_over(elm) {
  var arrayPageSize = getPageSize();
  var arrayPageScroll = getPageScroll();

  // center lightbox and make sure that the top and left values are not negative
  // and the image placed outside the viewport
  var lightboxTop = 150 + arrayPageScroll[1];
  var lightboxLeft = ((arrayPageSize[0] - $('message-box').getWidth()) / 2);

  $('message-box').style.top = (lightboxTop < 0) ? "0px" : lightboxTop + "px";
  $('message-box').style.left = (lightboxLeft < 0) ? "0px" : lightboxLeft + "px";
  $('message-box').style.zIndex = 101;
  // clear out the old form
  var old_content = $('message').firstChild;
  if (old_content) {
    $('message').firstChild.remove();
    // need to keep the old stuff safe
    $('holding-pen').appendChild(old_content);
  }

  // insert our form
  $('message').appendChild(elm);
  elm.show();

  // display the pop-over
  $('message-box').show();
}


var Dialog = {};
Dialog.Box = Class.create();
Object.extend(Dialog.Box.prototype, {
    initialize: function(id) {
      this.createOverlay();
  
      this.dialog_box = $(id);
      this.dialog_box.show = this.show.bind(this);
      this.dialog_box.persistent_show = this.persistent_show.bind(this);
      this.dialog_box.hide = this.hide.bind(this);
  
      this.parent_element = this.dialog_box.parentNode;
  
      this.dialog_box.style.position = "absolute";
  
      var e_dims = Element.getDimensions(this.dialog_box);
      var b_dims = Element.getDimensions(this.overlay);
  
      this.dialog_box.style.left = ((b_dims.width/2) - (e_dims.width/2)) + 'px';
      this.dialog_box.style.top = this.getScrollTop() + ((this.winHeight() - (e_dims.width/2))/2) + 'px';
      this.dialog_box.style.zIndex = this.overlay.style.zIndex + 1;
    },
  
    createOverlay: function() {
      if($('dialog_overlay')) {
        this.overlay = $('dialog_overlay');
      } else {
        this.overlay = document.createElement('div');
        this.overlay.id = 'dialog_overlay';
        Object.extend(this.overlay.style, {
        	position: 'absolute',
        	top: 0,
        	left: 0,
        	zIndex: 90,
        	width: '100%',
        	backgroundColor: '#000',
        	display: 'none'
        });
        document.body.insertBefore(this.overlay, document.body.childNodes[0]);
      }
    },
  
    moveDialogBox: function(where) {
      Element.remove(this.dialog_box);
      if(where == 'back')
        this.dialog_box = this.parent_element.appendChild(this.dialog_box);
      else
        this.dialog_box = this.overlay.parentNode.insertBefore(this.dialog_box, this.overlay);
    },
  
    show: function() {
      this.overlay.style.height = this.bodyHeight()+'px';
      this.moveDialogBox('out');
      
      this.overlay.onclick = this.hide.bind(this);
      	
      this.selectBoxes('hide');
      new Effect.Appear(this.overlay, {duration: 0.1, from: 0.0, to: 0.3});
      this.dialog_box.style.display = '';
  
    	this.dialog_box.style.left = '0px';
   
      var e_dims = Element.getDimensions(this.dialog_box);
    	
    	this.dialog_box.style.left = ((this.winWidth()/2) - (e_dims.width)/2) + 'px';
    	
      this.dialog_box.style.top = this.getScrollTop() + ((this.winHeight() - (e_dims.width/2))/2) -100 + 'px';
    	
    },
    
    getScrollTop: function() {
    	return (window.pageYOffset)?window.pageYOffset:(document.documentElement && document.documentElement.scrollTop)?document.documentElement.scrollTop:document.body.scrollTop;
    },
    
    persistent_show: function() {
      this.overlay.style.height = this.bodyHeight()+'px';
      this.moveDialogBox('out');
   
      this.selectBoxes('hide');
      new Effect.Appear(this.overlay, {duration: 0.1, from: 0.0, to: 0.3});
      
      this.dialog_box.style.display = '';
    	this.dialog_box.style.left = '0px';
      var e_dims = Element.getDimensions(this.dialog_box);
    	this.dialog_box.style.left = ((this.winWidth()/2) - (e_dims.width)/2) + 'px';
    	
    },
  
    hide: function() {
      this.selectBoxes('show');
      new Effect.Fade(this.overlay, {duration: 0.1});
      this.dialog_box.style.display = 'none';
      this.moveDialogBox('back');
      $A(this.dialog_box.getElementsByTagName('input')).each(function(e){if(e.type!='submit')e.value=''});
    },
  
    selectBoxes: function(what) {
      $A(document.getElementsByTagName('select')).each(function(select) {
        Element[what](select);
      });
  
      if(what == 'hide')
        $A(this.dialog_box.getElementsByTagName('select')).each(function(select){Element.show(select)})
    },
    
	bodyWidth: function() { return document.body.offsetWidth || window.innerWidth || document.documentElement.clientWidth || 0; },
	bodyHeight: function() { return document.body.offsetHeight || window.innerHeight || document.documentElement.clientHeight || 0; },
  
    winWidth: function() {
		 var viewportwidth;
		 
		 // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
		 
		 if (typeof window.innerWidth != 'undefined')
		 {
		      viewportwidth = window.innerWidth;
		 }
		 
		// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
		
		 else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0)
		 {
		       viewportwidth = document.documentElement.clientWidth;
		 }
		 
		 // older versions of IE
		 
		 else
		 {
		       viewportwidth = document.getElementsByTagName('body')[0].clientWidth
		 }
		 return viewportwidth;
    
     },
    winHeight: function() { 
		 var viewportheight;
		 
		 // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
		 
		 if (typeof window.innerHeight != 'undefined')
		 {
		      viewportheight = window.innerHeight
		 }
		 
		// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
		
		 else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientHeight != 'undefined' && document.documentElement.clientHeight != 0)
		 {
		       viewportheight = document.documentElement.clientHeight;
		 }
		 
		 // older versions of IE
		 
		 else
		 {
		       viewportheight = document.getElementsByTagName('body')[0].clientHeight;
		 }
		 return viewportheight;
	
    }
  
  }); 

// displays the given element in a popover shell
function pop_over_wide(elm) {
  var arrayPageSize = getPageSize();
  var arrayPageScroll = getPageScroll();

  // center lightbox and make sure that the top and left values are not negative
  // and the image placed outside the viewport
  var lightboxTop = 50 + arrayPageScroll[1];
  var lightboxLeft = ((arrayPageSize[0] - $('message-box-wide').getWidth()) / 2);

  $('message-box-wide').style.top = (lightboxTop < 0) ? "0px" : lightboxTop + "px";
  $('message-box-wide').style.left = (lightboxLeft < 0) ? "0px" : lightboxLeft + "px";
  
  // clear out the old form
  var old_content = $('message_wide').firstChild;
  if (old_content) {
    $('message_wide').firstChild.remove();
    // need to keep the old stuff safe
    $('holding-pen').appendChild(old_content);
  }

  // insert our form
  $('message_wide').appendChild(elm);
  elm.show();

  // display the pop-over
  $('message-box-wide').show();
}



function close_pop_over() {
  $('message-box').hide();
	$('message-box-wide').hide();
}

// move all the childLinks to their bigger containers above (bigLink) and add a pointer style
function moveLinkHigher(outerClass,innerClass) {
  $$(outerClass).each(function(x) {
    if ($(x).down(innerClass) && $(x).down(innerClass).down('a')) {
      $(x).addClassName("showHandPointer");
      $(x).observe('click', function() { window.location = $(x).down(innerClass).down('a').href; });
    }
  }); 
}

//livechat stuff

var chat_width = 494;
var chat_height= 418; //400;
var ptTimeOut= 30000;
var xmlHttp = null;

var cookieGuid = "gbbk4055ndbrmkattsqc2b45" ;
var mode = '1' ;
var strX ='20'
var strY ='30'
var DeptID = "";
var Agent = "";

str = "https://livechat06.volusion.com/?ID=190754";
str = str.toLowerCase();
idx = str.indexOf("/?id=");
 
var v_lc_domain = str.substring(0,idx);
var statsURL = v_lc_domain+"/statsupdater.aspx?Command=";
var cOrderID = str.substring(idx+5);
var strSRC = v_lc_domain + "/images/uploads/190754/OfflineButton.gif"; //+"?"+new Date(); 
var divImage;
 
var tType = ""; 
var documentURL =escape("");
var VolusionScriptError= "If you are getting this message, it is  because\r\na) The Volusion Live Chat javascript has been modified from its original code.\r\n(You must re-copy the script from the SETTINGS screen of your live chat software, and re-paste it to your website.\r\nor\r\nb) The Volusion Live Chat javascript is pasted more than once in this page.\r\n(Remove extra copy of this script on this page)";
var divImage;
var IS_IE = false;
var is_ff = false;
var postCount=0;    
var startPost = new Date();   
    

if(document.all) IS_IE = true;
else is_ff = true;

if(is_ff)
    chat_height += 4;


function LaunchVolusionChat(auto)
{
    var today = new Date();
    var request_url = v_lc_domain+"/livechat.aspx?ID="+cOrderID+"&location="+documentURL.toLowerCase()+"&auto="+auto+"&cookieGuid="+cookieGuid+"&DeptID="+DeptID+"&Agent="+Agent+"&tType="+tType;

    window.open( request_url, today.getTime(), 'scroll=yes,scrollbars=yes,menubar=no,resizable=0,location=no,screenX=50,screenY=100,width=' + chat_width + ',height='+chat_height ) ;
}


 
function AutoPrompt()
{
   DeptID = '0';
   url = statsURL + "ISPROMPTOK&OrderID="+cOrderID+"&DeptID="+DeptID+"&Do=Approve&dt="+new Date()+"&cookieGuid="+cookieGuid;
   // hln 
   //alert(url);
   document.getElementById("imgChat").src = url;
   
}




var __isFireFox = navigator.userAgent.match(/gecko/i);   
  
  
//returns the absolute position of some element within document   
function getElementAbsolutePos(obj){   
	var output = new Object();	
	var mytop=0;
	var myleft=0;	
	while(obj){		
		mytop+= obj.offsetTop;		
		myleft+= obj.offsetLeft;		
		obj= obj.offsetParent;
	}	
	output.x = myleft;	
	output.y = mytop;	
	return output;  
}  


function doscroll(){
	x=document.body.scrollHeight;
	x=x+9999;
	window.scrollTo(0,x);
}

