if(window.location.href.indexOf('www') == -1 && window.location.href.indexOf('demo7')== -1) window.location = 'http://www.viewplicity.com';

var isIE6 = /MSIE 6/i.test(navigator.userAgent);
var isIE7 = /MSIE 7/i.test(navigator.userAgent);
var isIE8 = /MSIE 8/i.test(navigator.userAgent);
var isSafari = /AppleWebKit/i.test(navigator.userAgent);
var origHash  = top.location.hash;
// Opening and closing of the drop down information

morphs = new Array();
function createMorph(elm,speed) {
	if(!speed) speed = 50;
	morphs[elm] = new Fx.Morph(elm, {wait: false, duration: speed, transition: Fx.Transitions.Sine.linear});
}

var closeInt = null;
var lastClose = null;
var initComplete = false;
function closeElement(elm) {
	closeIframe();
	if(elm.id) elm = elm.id;
	$(elm).style.height = '0px';
	$(elm).setStyle('opacity', '0');
	$('overlay').style.display = 'none';
//	if(elm != 'content' && !closeInt && initComplete) closeInt = setTimeout(function(){ $('content').style.display = 'block'; closeInt = null; },1000);
	lastClose = elm;
}
function openElement(elm) {
	if(closeInt) {clearTimeout(closeInt); closeInt = null; }
	if(elm == 'homeText') {$('content').style.display = 'block'; $('overlay').style.display = 'none'; return;}
	if(elm.id) elm = elm.id;
	$('content').style.display = 'none';
	$('overlay').style.display = 'block';
	var oldHeight = $(elm).getStyle('height');
	$(elm).style.height = '600px';
	var newHeight = $(elm).offsetHeight - $(elm).getStyle('padding-top').toInt() - $(elm).getStyle('padding-bottom').toInt();
	$(elm).style.height = newHeight;
	$(elm).setStyle('opacity', '1');
}
function closeIframeOverlay(elm) {
	closeElement(elm);
}
var firstClick = false;
var delayedSect = null;
function dropDowns(sect) {
	if(!firstClick){
		delayedSect = sect;
		return;
	}
	if(hist.getCurrentHash() == sect) return;
	checkLastAction(sect);
	hist.addState(sect);
	openElement(sect + 'Text');
	lastAction = sect;
}

// Some page initializations and what-not
   var text = $('textChange');
   var goBack = $('goBack');
   var faqScroll, prev;
   var scrollBar = false;

   var cMorph = new Fx.Morph($('carouselHome'));
   var textMorph = new Fx.Morph(text);
   var learnMoreGraphicMorph = new Fx.Morph($('learnMoreGraphic'));
   var supportMorph = new Fx.Morph($('overlay'), {duration: 'long', transition: Fx.Transitions.Quad.easeInOut});
   var initMultiBox;
   var mf;

   var currTryItState = 0;

   var hist = new HistoryManager();


// Undoes the previous action
var lastAction = false;
var redirectInProg = false;
function checkLastAction(redirect) {
	var mbc = $$('.MultiBoxContent');
   	if(mbc && mbc.length>=1 && mbc[0].innerHTML.length > 1 && !redirectInProg && lastAction == "tryIt" && flashCheckPassed && browserCheck()){
		var ap;
		if(typeof(redirect)!='undefined') ap = redirect; else ap = '';
		if(ap == '' && hist.getCurrentHash()!='tryIt') ap = hist.getCurrentHash();
		if(ap == '') ap = 'home';
		var currquery = location.search.substring(1);
		var d = new Date();
		top.location.href = 'index.html?'+d.getTime()+'#/'+ap;
		redirectInProg = true;
	}
	if (lastAction == "buyNow")
		closeElement('buyNowText');
	if (lastAction == "support")
		closeElement('supportText');
	if (lastAction == "tours")
		closeElement('toursText');
	if (lastAction == "learn")
		closeElement('learnText');
	if (lastAction == "tryIt"){
	}
	if (lastAction && lastAction.indexOf("learnMore") > -1)
		learnMoreToggle("close");
	lastAction = false;
}
var tabs = { buyNow: 'buyNow', support: 'footerIconSupport', learn: 'learn', tours: 'tours', home: 'home' };
var activeTab;
function setActiveTab(){
	var tab = hist.getCurrentHash();
	activeTab = tab;
	if(origPage != 'index' && tab=='') tab = origPage;
	if(tab == '') tab = 'home';
	for(var i in tabs){
		if(i == tab) $(tabs[i]).parentNode.className = 'active'; else $(tabs[i]).parentNode.className = '';
	}	
}
// Creates the events for back/forward browser buttons
hist.addEvent('onHistoryChange', function()
{
	checkLastAction();
	if (hist.getCurrentHash() == "buyNow")
	{
		openElement('buyNowText');
		lastAction = 'buyNow';
	}
	else if (hist.getCurrentHash() == "learn")
	{
		openElement('learnText');
		lastAction = 'learn';
	}
	else if (hist.getCurrentHash() == "support")
	{
		openElement('supportText');
		lastAction = 'support';
	}
	else if (hist.getCurrentHash() == "home" || hist.getCurrentHash() == '')
	{
		openElement('homeText');
		lastAction = 'home';
	}
	else if (hist.getCurrentHash() == "tours")
	{
		openElement('toursText');
		lastAction = 'tours';
	}
	else if (hist.getCurrentHash() == "faq")
	{
		openElement('faqText');
		lastAction = 'faq';
	}
	else if (hist.getCurrentHash() == "tryIt" && $('tryit'))
	{
		lastAction = 'tryIt';
	}
	else if (hist.getCurrentHash().indexOf("learnMore") > -1)
	{
		learnMoreToggle("open");
		lastAction = hist.getCurrentHash();
	}
	else if (hist.getCurrentHash().substr("carousel"))
	{
		lastAction = hist.getCurrentHash();
	}
	else
	{
		$('content').style.display = 'block';
		lastAction = hist.getCurrentHash();
	}
	setActiveTab();
});

var origLoc = location.search.substring(1);
var origPage;

window.addEvent('load', function() {
	
	origPage = document.location.toString().split('/site/')[1].split('.')[0];
	if(origPage == origHash) origPage = 'index';
	if(origPage == 'promo' || origPage == 'promo2') origPage = 'index';
	
	if(origPage != 'promo' && origHash != 'promo' && origPage != 'promo2'){
		$$('.nav').each(function(nav){
			nav.style.display = 'block';
		 });
	}
	else{
		$('promo').style.display = 'block';
	}

	var gt = $('tourCollection');
	var tmpc = '';
	for(var i=0;i<desc.length;i++){
		var tmp = tourTemplate.replace(/%1/g,""+i);
		tmp = tmp.replace('%2',desc[i]);
		gt.innerHTML += tmp;
	}

	$('buyNow').addEvent('click',function() {
		dropDowns('buyNow');
	}).removeProperty('href');
	$('home').addEvent('click',function() {
		dropDowns('home');
	}).removeProperty('href');
	$('tours').addEvent('click',function() {
		dropDowns('tours');
	}).removeProperty('href');
	if($('tours2')) $('tours2').addEvent('click',function() {
		dropDowns('tours');
	}).removeProperty('href');
	$('vptours').addEvent('click',function() {
		dropDowns('tours');
	}).removeProperty('href');
	$('buyNow2').addEvent('click',function() {
		dropDowns('buyNow');
	}).removeProperty('href');
	$('goBackBuyNow').addEvent('click', function() {
		dropDowns('buyNow');
   }).removeProperty('href');
	$('learn').addEvent('click',function() {
		dropDowns('learn');
	}).removeProperty('href');
	if($('learn2')) $('learn2').addEvent('click',function() {
		dropDowns('learn');
	}).removeProperty('href');
	$('footerIconSupport').addEvent('click', function()	{
		dropDowns('support'); 
   }).removeProperty('href');
   $('goBackOverlay').addEvent('click', function() {
		dropDowns('support');
	});

	$$('.subItem').each(function(sub){
		closeElement(sub.id);
	 });
	
   $('logo').addEvent('click', function() {
		checkLastAction();
		hist.addState('home');
		lastAction = false;
   });
	
	// Handles all the multibox events
	initMultiBox = new multiBox({
		mbClass: '.mb',
		container: $('multi'),
		useKeyboard: 'false',
		offset: {x:0, y:0},
		openFromLink: false,
		fixedTop: 95
	});
	if($('tryit')) {
			$('tryit').addEvent('click', function() {
			checkLastAction('tryIt');
			if(hist.getCurrentHash() == "tryIt")
			{
				hist.addState('home');
				lastAction = false;
			}
			else 
			{
				hist.addState('tryIt');
				lastAction = 'tryIt';
			}
	   });
	}
   $$('.MultiBoxClose')[0].addEvent('click', function() {
		initMultiBox.close();
		if($('content').display!='block') $('overlay').style.display = 'block';
		if(lastAction != 'tryIt') return;
		checkLastAction();
        hist.addState('home');
		lastAction = false;
		self.scrollTo(0,0);
   });
	
	(function() { $('overlay').style.display = 'none'; }).delay(1000);
	
	if(origPage != 'index') page = origPage; else page = origHash;
	if(page == '') page = 'home';
	hist.addState(page);
	(function() { 
		  (function(){
		  var page;
		  if(origPage != 'index') page = origPage; else page = origHash;
		  if (page.indexOf('tryIt')!=-1) {
		    vp_fireEvent($('tryit'));
		  }
		  else if (page.indexOf('support') != -1) {
			$('footerIconSupport').fireEvent('click');
		  }
		 else if (page.indexOf('learn') != -1) {
			$('learn').fireEvent('click');
		  }
		 else if (page.indexOf('tours') != -1) {
			$('tours').fireEvent('click');
		  }
		  else if (page.indexOf('buyNow') != -1) {
			$('buyNow').fireEvent('click');
		  } else { $('content').style.display = 'block'; setActiveTab(); }
		  firstClick = true;
		  if(delayedSect){
			dropDowns(delayedSect);
			delayedSect = null;	
			}
		}).delay(1000);		
				
	  }).delay(1000);

	  if(document.body.scrollHeight <= 600)
	  {
//			document.body.style.overflow = "auto";
//			$('content').style.marginTop = 0;
      }
	  checkPageLayout();
//	  self.scrollTo(0,0);
//      showloggedout();
	  $('vppaypal').style.display = 'none';
	  $('vppaypal2').style.display = 'none';
	  $('vppaypal3').style.display = 'none';
//	  (function(){setActiveTab()}).delay(500);
	  (function(){$('portal').src = "loginchk.php"}).delay(500);
	  initComplete = true;
});

window.addEvent('domready', function()
{
   $(document.body).addEvent('mousewheel', function(e)
   {
      e.stop();
   });
});

var carouselhome;
function learnMoreToggle(option)
{
	var learnMoreGraphic = $('learnMoreGraphic' + mf.index);
	var learnMoreGraphicMorph = new Fx.Morph(learnMoreGraphic);
	if (option =='open'){
      populateTextInstant(mf.index);
	  if(isIE7) $('textChange').getElements('.nodeText')[0].getElements('.leadPara')[0].setStyle('display','none');
      (function ()
      {
         if ($$('.scrollControlsY')[0]) $$('.scrollControlsY')[0].dispose();
         if (!scrollBar) scrollBar = new MooScroll({ selector: '#textChange' });
         $$('.scrollControlsY')[0].setStyle('display', 'block');
         scrollBar.refresh();
		 startAutoScroll(scrollBar);
      }).delay(600);

      // Animate the header graphic
      // Move the Carousel up

      learnMoreGraphic.setStyle('display', 'block');
      learnMoreGraphic.setStyle('height', '1px');
      learnMoreGraphic.setStyle('opacity', '0');
      learnMoreGraphic.setStyle('visibility', 'hidden');
      learnMoreGraphic.setStyle('display', 'block');
	  $('carouselHome').style.visibility = "hidden"; 
	  learnMoreGraphic.setStyle('height', '181px');
	  learnMoreGraphic.setStyle('opacity', '1');
	  carouselhome = $('carouselHome').offsetTop;
	  learnMoreGraphic.setStyle('marginTop','0px');

		$('carouselHome').style.display = 'none';
	  $('carouselHome').setStyle('height', '1');
	  $('carouselHome').setStyle('opacity', '0');
	  $('MooFlow').style.display = "none";

	  $('imageChange').style.display = 'block';

      // Open up the text box
      textMorph.start({ height: '210px' });

      // Fade the learn more and fade in go back
	$('goBack').setStyle('display','block');
	  $('goBack').setStyle('opacity','0');
	  $$('.learnMore').each(function(learnMores){
			learnMores.setStyle('display','none');
       });
   }
	else {
	  $('MooFlow').style.display = "block";
	  if(isIE6) $('text').style.marginTop = "-30px";

      $$('.scrollControlsY').each(function(scroller)
      {
         scroller.setStyle('display', 'none');
      });

	  if(scrollBar) stopAutoScroll();
	  learnMoreGraphic.setStyle('visibility', 'hidden');
	  learnMoreGraphic.setStyle('display', 'none');
	  $('carouselHome').style.display = 'block';
	  $('carouselHome').setStyle('top','0px');
	  $('carouselHome').setStyle('height', '200px');
	  $('carouselHome').setStyle('opacity', '1');
	  $('MooFlow').style.display = "block";
	 $('imageChange').style.display = 'none';
	  if(isIE7) $('textChange').getElements('.leadPara')[0].style.display = 'block';
	  restoreText();
	  var lph = $('textChange').getElements('.leadPara')[0].offsetHeight + 'px';
      textMorph.start({ height: lph });
      scrollBar = false;
	  $('goBack').setStyle('display','none');
	  $$('.learnMore').each(function(learnMores){
			learnMores.setStyle('display','block');
       });
	  $('textChange').getElements('.learnMore').each(function(learnMores){
	    learnMores.addEvent('click', function(){
           checkLastAction();
           learnMoreToggle("open");
           hist.addState('learnMore' + mf.index);
           lastAction = hist.getCurrentHash();
	    });
      });
   }
}

function alignMultiBox()
{
	var mbc = $$('.MultiBoxContainer');
   	if(mbc && mbc.length>=1 && mbc[0].innerHTML.length > 1)
      initMultiBox.alignBox();
}

var lastTextChange = null;

function restoreText(){
	if($('textChange').getElement('.nodeText') && lastTextChange) $('textChange').innerHTML = lastTextChange;
}

function populateText(index)
{
   var n = index;
   $('textChange').fade(0);
   (function()
   {
//      if (parseInt($('textChange').getStyle('height')) > 105) learnMoreToggle();
	  if($('textChange').getElement('.nodeText') && lastTextChange) $('textChange').innerHTML = lastTextChange;
	  if($('textChange').getElement('.nodeText')) $('textDock').appendChild($('textChange').getElement('.nodeText'));
	  $('textChange').innerHTML = "";
      $('textChange').appendChild($('node' + index + 'Text'));
	  lastTextChange = $('textChange').innerHTML;
	  learnMoreToggle('close');

   }).delay(500);

   (function()
   {
      $('textChange').fade(1);
   }).delay(500);
}

function populateTextInstant(index)
{
	  if($('textChange').getElement('.nodeText') && lastTextChange) $('textChange').innerHTML = lastTextChange;
	  if($('textChange').getElement('.nodeText')) $('textDock').appendChild($('textChange').getElement('.nodeText'));
	  $('textChange').innerHTML = "";
      $('textChange').appendChild($('node' + index + 'Text'));
	  lastTextChange = $('textChange').innerHTML;
}

// Temporarily stops an even from firing for a specified time
function pauseEvent(ele, event, time)
{
   if (ele.id) ele = ele.id;
   var tmpEle = new Element('div');
   tmpEle.cloneEvents($(ele), event);
   $(ele).removeEvent(event);

   (function()
   {
      $(ele).cloneEvents(tmpEle, event);
   }).delay(time);
}

var scrollInterval = null;
var autoScrollbar = null;
var autoScrollpos;
var lastScrollpos = 0;
var lastScrollAttempt = 0;
function startAutoScroll(scrollbar){
	return;
	if(!scrollInterval){
		autoScrollbar = scrollbar;
		scrollInterval = setInterval('autoScroll();',130);
		autoScrollpos = 0;
		lastScrollpos = 0;
		lastScrollAttempt = 0;
		$('textChange').getElements('.scrollBar')[0].addEvent('click',stopAutoScroll);
		$('text').addEvent('click',stopAutoScroll);
	}
}
function stopAutoScroll(scrollbar){
	return;
	clearInterval(scrollInterval);
	scrollInterval = null;
	$('textChange').getElements('.scrollBar')[0].removeEvent('click',stopAutoScroll);
	$('text').removeEvent('click',stopAutoScroll)
}
function autoScroll(){
	autoScrollbar.setSlider(autoScrollpos);
	autoScrollpos += 1;
	var ls = $('textChange').getElements('.scrollHandle')[0].offsetTop;
	if(ls!=lastScrollpos) {lastScrollpos = ls; lastScrollAttempt = autoScrollpos;} else {
		if(autoScrollpos > lastScrollAttempt+10) stopAutoScroll();
	}
}

function resizeIframe(width,height){
	initMultiBox.contentObj.height = height+20;
	initMultiBox.contentObj.width = width+20;
	initMultiBox.contentContainer.height = height+20;
	initMultiBox.contentContainer.width = width+20;
	initMultiBox.contentContainer.style.height = height+20;
	initMultiBox.contentContainer.style.width = width+20;
	initMultiBox.contentContainer.getElement('iframe').height = height+20;
	initMultiBox.contentContainer.getElement('iframe').width = width+20;

	alignMultiBox();
	$('overlay').style.display = 'none';
}

function logout(){
	$('portal').src='logout.php';
	showloggedout();
}

function home(){
	top.location.href = 'index.html';
}

function flashVersionCheckFailed() {
	flashCheckPassed = false;
	closeIframe();
	afterlogin('');
}

var vp_loggedIn = false;
function afterlogin(username){
	if(typeof(username)!='undefined' && username!=''){
		$('loginbut').style.display = 'none';
		$('logoutbut').style.display = 'block';
		$('registerbut').style.display = 'none';
//		$('accountbut').style.display = 'block'; 
		$('welcome').innerHTML = '  Welcome, '+username;
		$('welcome').style.display = 'block';
		$('topMenu').style.visibility = 'visible';
	}
	setTimeout('FLASHCHECK_checkVersion();',10);
	setTimeout('vp_checkpp();',10);
	afterAuthCheck(true);
	if (!browserCheck() || !flashCheck()) {
		logout();
		return false;
	}
	return true;
}

function showloggedout(){
	$('loginbut').style.display = 'block';
	$('logoutbut').style.display = 'none';
	$('registerbut').style.display = 'block';
//	$('accountbut').style.display = 'none';
	$('welcome').style.display = 'none';
	$('topMenu').style.visibility = 'visible';
	afterAuthCheck(false);
	closeIframe();
}

function afterAuthCheck(state){
	vp_loggedIn = state;
	vp_checkingAuth = false;
}

function closeIframe(){
	if($('content').display!='block') $('overlay').style.display = 'block';
	if(!$('MultiBoxContentContainer')) return;
	if(vp_registering && vp_checkingAuth) {setTimeout("closeIframe();",200); return; }
	if(vp_registering && vp_loggedIn && initMultiBox.contentObj.url.indexOf("register")==-1) {
		vp_registering = false; 
	    initMultiBox.contentContainer.getElement('iframe').src = initMultiBox.contentObj.url;
	 	return; 
	}
	vp_registering = false;
	var mb = $$('.MultiBoxClose');
	if(mb && mb.length>0) mb[0].fireEvent('click');
}

var vp_checkingAuth = false;
function recheckAuth(){
	vp_checkingAuth = true;
	$('portal').src = "loginchk.php";
}

var smallStyle = false;
var prevStyle = false;
var winSz = null;
function checkPageLayout(){
	winSz = window.size();
	var bd = $(document.body);
	smallStyle = winSz.width < 1280;
	if(!smallStyle){
		bd.style.width ='100%';
	}
	else{
		bd.style.width = '1280px';
	}
	smallStyle = winSz.height < 760;
	if(!smallStyle){
		bd.style.height ='100%';
	}
	else{
		bd.style.height = '760px';
	}
	if(prevStyle != smallStyle) self.scrollTo(0,0);
	prevStyle = smallStyle;
	alignMultiBox();
}

window.size = function()
{
	var w = 0;
	var h = 0;

	//IE
	if(!window.innerWidth)
	{
		//strict mode
		if(!(document.documentElement.clientWidth == 0))
		{
			w = document.documentElement.clientWidth;
			h = document.documentElement.clientHeight;
		}
		//quirks mode
		else
		{
			w = document.body.clientWidth;
			h = document.body.clientHeight;
		}
	}
	//w3c
	else
	{
		w = window.innerWidth;
		h = window.innerHeight;
	}
	return {width:w,height:h};
}

window.center = function()
{
	var hWnd = (arguments[0] != null) ? arguments[0] : {width:0,height:0};

	var _x = 0;
	var _y = 0;
	var offsetX = 0;
	var offsetY = 0;

	//IE
	if(!window.pageYOffset)
	{
		//strict mode
		if(!(document.documentElement.scrollTop == 0))
		{
			offsetY = document.documentElement.scrollTop;
			offsetX = document.documentElement.scrollLeft;
		}
		//quirks mode
		else
		{
			offsetY = document.body.scrollTop;
			offsetX = document.body.scrollLeft;
		}
	}
	//w3c
	else
	{
		offsetX = window.pageXOffset;
		offsetY = window.pageYOffset;
	}

	_x = ((this.size().width-hWnd.width)/2)+offsetX;
	_y = ((this.size().height-hWnd.height)/2)+offsetY;

	return{x:_x,y:_y};
}

location.vp_getQueryValue = function(key) {
    key += "=";
    var values = this.search.substring(1).split("&");
    for (var i = 0; i < values.length; i++) {
      if (values[i].indexOf(key) === 0) {
        return values[i].substring(key.length);
      }
    }
    return null;
  };

  function vp_fireEvent(target){
	  var obj = new Object();
	  obj.bubbles = false;
	  obj.cancelable = false;
	  obj.currentTarget = target;
	  obj.eventPhase = 2;
	  obj.target = target;
	  obj.timeStamp = 0;
	  obj.type = 'click';
	  obj.preventDefault = function() {};
	  obj.stopPropagation = function() {};
	  obj.srcElement = target;
	  target.fireEvent('click',obj);
	};

  var vp_checkpp_processed = false;
  function vp_checkpp() {
	  if (!vp_checkpp_processed) {
		  var pp = null;
		  if ((location.vp_getQueryValue('paypal') == 'success')) {
			  pp = $('vppaypal');
		  }
		  if ((location.vp_getQueryValue('cancelled') == 'true')) {
			  pp = $('vppaypal2');
		  }
		  if ((location.vp_getQueryValue('promo') == '2')) {
			  pp = $('vppaypal3');
			  pp.href = promoTemplate2;
		  }
		  if ((location.vp_getQueryValue('promo') == '3')) {
			  pp = $('vppaypal3');
			  pp.href = promoTemplate3 + "&dn=" + location.vp_getQueryValue('dn');
		  }
		  if ((location.vp_getQueryValue('promo') == '4')) {
			  pp = $('vppaypal3');
			  pp.href = promoTemplate4 + "&dn=" + location.vp_getQueryValue('dn');
		  }
		  if (pp != null) {
			 vp_fireEvent(pp);
		  }		  
		  vp_checkpp_processed = true;
	  }
  }

var vp_registering = false;
function setRegistering(){
	vp_registering = true;
}

var desc = ['Viewplicity Overview', 
	'Basic functions - adding camera and testing by selecting to watch yourself', 
	'Inviting another web site user to join your group',
	'Watching another member\'s live camera broadcast and adding another camera',
	'Recording a video / manipulate player view sizing',
	'Another user posts a video in the group archive for you to watch',
	'Sending and receiving text messages',
	'Control toolbar message flashing for incoming message alert',
	'Deleting video archive entries',
	'Adding new groups and switching groups',
	'Drag / drop of archive components' ];

var tourTemplate =	'<l1><a href="http://www.viewplicity.com/site/support/index.php?page=kb_view&id=37#%1" rel="[loginGroup],width:1,height:1,ajax:true" id="vptours%1" class=" vptour mb" title="Video Tours">%2</a></li><br />';

var promoTemplate2 = 'paypal.php?action=success&paypal=success&promo=2';
var promoTemplate3 = 'buy.php?id=1&promo=3';
var promoTemplate4 = 'buy.php?id=1&promo=4';

