//IMPORTANT
//Use this namespace shortcut when working with jQuery.
//This is to prevent conflicts with some pages still using PrototypeJS
var $j = jQuery;

/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Description: 		Store common helper functions
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */


var ord=Math.random()*10000000000000000;
ord = ord=Math.round(ord);
function noCache(){return 'nc=' + (Math.random(0,1000) + '').replace('0.', '');};

//Cookies
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function getFolderName() {
	var x = window.location.href.split('://')[1].split('/');
	var f = x[1];
	if(f=="") {
		var g = getPageName();
		if(g=="index-html"){
			f="homepage";
		}
	}
	return f;
};	

function getPageName() {
	var x = window.location.href.lastIndexOf('/')+1;
	var y = window.location.href.length;
	//var z = "homepage"
	var z = "index.html"
	if(x<y) {
		z = window.location.href.substring(x,y);
	}
	//z = z.replace("#","-");
	//z = z.replace("?name=","?;name=");
	z = z.replace(/\./g, "-");
	return z;
};

function newWindow(wURL,wName,wWidth,wHeight,wScroll,wResizable,wCentered){
	var settings = 'height='+wHeight+',width='+wWidth+'scrollbars='+wScroll+',resizable='+wResizable;
	if(wCentered==true){
		lPosition	= (screen.width) ? (screen.width-wWidth)/2 : 0;
		tPosition	= (screen.height) ? (screen.height-wHeight)/2 : 0;	
		settings	+= ',left=' + lPosition + ',top=' + tPosition;
	}
	var nWindow	= window.open(wURL,wName,settings);
	nWindow.focus();
};


/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Description: 		Store General functions
/* Dependancies: 		jquery1.6.2(CDN), plugins.js
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */

// Suckerfish Dropdown Menu
// Uses object detection to load for IE only
var sfHover = function() {
	var sfEls = $j('#nav li')
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
};
if (window.attachEvent) window.attachEvent("onload", sfHover);

$j(function(){
  RCCS = (window.RCCS !== undefined ? window.RCCS : {});

  // Dynamic Lead
  var wrapper = $j('#dynamic-lead-wrapper');
  if (wrapper.length) {
    RCCS.dl = {
      // Commonly searched-for elements:
      wrapper : wrapper,
      element : $j('#dynamic-lead', this.wrapper),
      modules : $j('#dynamic-lead-modules', this.wrapper),
      menuItem : $j('#menu-item-76, #menu-item-100, #menu-item-683, #menu-item-685'),
      // Animation settings that may change in the future:
      height : '352px',
      width : '1000px',
      marginBottom : '20px',
      speed : 1000,
      // Flowplayer settings:
      flowPlayer : {
        src : RCCS.pathToTheme + '/media/swf/flowplayer.commercial-3.2.7-6.swf',
        wmode : 'transparent'
      },
      // Open the Dynamic Lead Viewer
      open : function(url) {
      	var url = (url ? url : $j('a:first', this.modules).attr('href'));
      	if (this.wrapper.is('.open')) {
      	  return RCCS.dl.load(url);
      	};
      	if (RCCS.toggle !== undefined) {
      	  RCCS.toggle.close();
      	};
      	this.element.animate({
      		height: RCCS.dl.height,
      		width: RCCS.dl.width,
      		marginBottom: RCCS.dl.marginBottom
      		}, RCCS.dl.speed, 'linear', function(){
      		  RCCS.scrollTo(RCCS.dl.element);
      		  RCCS.dl.load(url);
      		}
      	).parent().addClass('open');
      	this.menuItem.addClass('current-menu-item');
      },
      // Close the Dynamic Lead Viewer
      close : function(resetHash) {
        if (resetHash !== undefined && resetHash) {
  	      window.location.hash = '!';
  	    };
      	$j('div:first-child', this.element).remove();
      	this.wrapper.removeClass('open');
      	this.element.animate({
      	  height: 0,
      		width: 0,
      		marginBottom: 0
      	}, RCCS.dl.speed, 'linear');
      	$j('li', this.modules).removeClass('active');
      	this.menuItem.removeClass('current-menu-item');
      	return false;
      },
      initVideo : function(videoUrl) {
        if (videoUrl.length) {
          $j('#viewer', this.element).html('<div id="player-wrapper"><a href="' + videoUrl + '" id="player"></a></div>');
          flowplayer('player', this.flowPlayer, {
			key: '#$91341f81958ea47f7a4', //radiocitychristmas.com domain key
			play: {
				url: RCCS.pathToTheme + '/media/swf/play.png',
				width: 81,
				height: 82,
				opacity: 1
			}
		  });
        };
      },
      load : function(url) {
        this.element.html('<div class="ajax-loader"></div>');
    		$j.ajax({
    		  url : url,
    		  cache : false,
    		  success : function(response, status, xhr){
    		    RCCS.dl.element.html(response);
    		    var thumbsWrapper = $j('#thumbnails-wrapper');
    		    var thumbs = $j('#thumbnails', thumbsWrapper);
            var thumbsWrapperWidth = parseInt(thumbsWrapper.width()) + 5;
            var thumbsWidth = $j('li:first', thumbs).outerWidth(true) * $j('li', thumbs).length;
    		    var browsers = $j('#gallery-right a.browse');
    		    var leftBrowser = browsers.filter('.left');
    		    var rightBrowser = browsers.filter('.right');
            var wrap = $j('#viewer');

            // Carousel
            leftBrowser.addClass('disabled');
            if (thumbsWidth <= thumbsWrapperWidth) {
              rightBrowser.addClass('disabled');
            };
            browsers.click(function(e){
              if (!$j(this).is('.disabled')) {
                var direction = $j(e.target).is('.left') ? 'left' : 'right';
                var moveThumbs = thumbs.css('left').replace('px', '');
                moveThumbs = (moveThumbs == 'auto' ? 0 : parseInt(moveThumbs));
                direction == 'left' ? moveThumbs += thumbsWrapperWidth : moveThumbs -= thumbsWrapperWidth;
                // if (moveThumbs + thumbsWrapperWidth < thumbsWidth && moveThumbs > -thumbsWidth) {
                  thumbs.animate({left : moveThumbs}, 400, function(){
                    if (thumbs.offset().left < thumbsWrapper.offset().left) {
                      leftBrowser.removeClass('disabled');
                    } else {
                      leftBrowser.addClass('disabled');
                    };
                    if (thumbs.offset().left + thumbsWidth > thumbsWrapper.offset().left + thumbsWrapperWidth) {
                       rightBrowser.removeClass('disabled');
                    } else {
                       rightBrowser.addClass('disabled');
                    };
                  });
                // };
              };
            });
            var videoUrl = $j.trim($j('#thumbnails a.active').siblings('.image-video').text());
            RCCS.dl.initVideo(videoUrl);

            // Thumbnails
          	$j('#thumbnails a').click(function(e) {
          		if ($j(this).hasClass('active')) { return false; }

          		var img = $j(this).siblings('div.image-large').find('img');
          		var title = img.attr('alt');
          		var description = img.parent().siblings('.image-description').text();
          		var videoUrl = $j.trim(img.parent().siblings('.image-video').text());

          		if (videoUrl) {
          			RCCS.dl.initVideo(videoUrl);
          		}
          		else {
          			wrap.html(img.clone());
          		};

          		$j('#title').html(title);
				$j("#description").html(description);
          		Cufon.replace('#title');
          		//Activate item
          		$j('#thumbnails a').removeClass('active');
          		$j(this).addClass('active');

          		return false;
          	}).tooltip({
          		track: true,
          		delay: 0,
          		showURL: false,
          		opacity: 1,
          		bodyHandler: function(){
          			var tooltip = $j('img', this).attr('alt');
          			return tooltip;
          		}
            });

			/* Tweet Thi Button
			var shareUrl = encodeURIComponent(window.location.href);
			var shareVia = "getspectacular"; //twitter handle to credit this tweet to
			var shareText = $j('#dynamic-lead-modules li.active div span a').text();
			var shareRelated = "rockettes"; //recommend a twitter acct to follow
			var shareThis = 'http://twitter.com/share?url=' + shareUrl + '&via=' + shareVia + '&text=' + shareText + '&related=' + shareRelated;

			$j('#details').append('<a href="#" class="tweet">Tweet</a>');
			$j('.tweet').click(function() {
				newWindow(shareThis,'TwitterShare',600,400,false,false,true);
				return false;
			});
			*/
		

            // Need to activate cufon again
			Cufon.set('fontFamily', 'DIN-Bold');
			Cufon.replace('#title');

          	// Close button
          	$j('#close', RCCS.dl.element).click(function(){
          	  RCCS.dl.close(true);
          	  return false;
          	});
    		  },
    		  error : function(jqXHR, textStatus, errorThrown){
    		    RCCS.dl.element.html('<div class="ajax-error">An error occurred trying to load this gallery. Please refresh the page and try again.</div>');
    		  }
    		});
      }
    };
  };

  // Togglable area that interacts with Dynamic Lead (ie. Guest Experiences)
  var toggle = $j('.toggle');
  if (toggle.length) {
  	RCCS.toggle = {
  	  element : toggle,
  	  trigger : $j('.trigger'),
  	  menuItem : $j('#menu-item-77'),
      hash : 'guest-experiences',
  	  speed : 400,
  	  open : function(){
  	    if (RCCS.dl !== undefined) {
  	      RCCS.dl.close();
  	    };
  	    window.location.hash = this.hash;
  	    this.menuItem.addClass('current-menu-item');
  	    this.trigger.addClass('active');
  	    this.element.slideDown(this.speed, function(){
  	      // Scroll to the element if it's out of view:
  	      var toggleTop = $j(this).offset().top;
      		var toggleBottom = toggleTop + $j(this).outerHeight();
      		// Get the height of the sticky bar
      		var stickyHeight = $j('#sticky-footer').outerHeight();
          if (toggleBottom > ($j(window).scrollTop() + $j(window).height() - stickyHeight)) {
    				$j(window).scrollTo(toggleBottom - $j(window).height() + stickyHeight, 800, {
    					axis : 'y'
        		});
      		};
        });
  	  },
  	  close : function(resetHash){
  	    if (resetHash !== undefined && resetHash) {
  	      window.location.hash = '!';
  	    };
  	    this.trigger.removeClass('active');
  	    this.element.slideUp(this.speed);
  	    this.menuItem.removeClass('current-menu-item');
  	  }
  	};
  };

  // Scroll to an element that's below the viewable area
	RCCS.scrollTo = function(element){
	  // Get position of the bottom of the element we're showing, relative to the window
	  var elementTop = element.offset().top;
    var elementBottom = elementTop + element.outerHeight();
    // Get the height of the sticky bar
    var stickyHeight = $j('#sticky-footer').outerHeight();
    // Get the window's height and scroll position:
    var windowHeight = $j(window).height();
    var scrollTop = $j(window).scrollTop();
    if (elementBottom > (scrollTop + windowHeight - stickyHeight) || elementTop < scrollTop) {
      $j(window).scrollTo(elementTop - 20, 800, {
        axis : 'y'
      });
    };
	};

  // Attach behaviors

  // Dynamic Lead:
  if (RCCS.dl !== undefined) {
    $j('body').addClass('dynamic-lead-page');
  	$j('li', RCCS.dl.modules).click(function(e){
  	  var link = $j('a', this);
  	  if ($j(this).is('.active')) { return false; };
  	  $j(this).addClass('active').siblings().removeClass('active');
  		RCCS.dl.open(link.attr('href'));
  		// Simulate deep-linking, pt. 1: hit the hash without hitting the full url
  		// (modules link to actual pages for graceful degradation)
  		window.location.hash = link.attr('href').substring(link.attr('href').indexOf('#'));
  		return false;
  	}).find('a').each(function(){
  	  this.href += (this.href.indexOf('?') ? '&ajax_load_gallery=1' : '?ajax_load_gallery=1');
  	  // Simulate deep-linking, pt. 2: create hash on the fly based on title value.
  	  var hash = $j(this).text().toLowerCase().replace(/[^a-z 0-9]+/g, '').replace(/[ ]+/g, '-');
  	  if (hash == 'see-whats-new' || hash == 'the-2011-spectacular') hash = 'about';
  	  this.href += '#' + hash;
  	  this.id = 'dynamic-lead-module-' + hash;
  	});
  	// Clicking on menu that corresponds to the Dynamic Lead:
  	$j('a:first', RCCS.dl.menuItem).click(function(){
  	  $j('li:first', RCCS.dl.modules).trigger('click');
  	  return false;
  	});
  	// Simulate deep-linking, pt. 3: check for a hash value on page load and trigger a click if there is one.
    if (window.location.hash && window.location.hash != '#!') {
      $j('#dynamic-lead-module-' + window.location.hash.substring(1), RCCS.dl.modules).trigger('click');
    };

	//trigger specific dl module 'behind the tradition'
	$('#menu-item-684, #menu-item-686').click(function() {
	 	$j('#dl-mod-5').trigger('click');
	});
	
	//trigger specific dl module when clicking home banner on ny
	$('#home-banner-link').click(function() {
	 	$j('#dl-mod-4').trigger('click');
	});
	
	//trigger specific dl module when clicking home banner on nt
	$('#home-banner-nt-link').click(function() {
	 	$j('#dl-mod-7').trigger('click');
	});
	
	
	
	

  };

  // Toggle:
  if (RCCS.toggle !== undefined) {
  	RCCS.toggle.trigger.click(function(){
  	  if ($j(this).is('.active')) {
  	    RCCS.toggle.close(true);
  	  } else {
  	    RCCS.toggle.open();
  	  };
  	  return false;
  	});
  	$j('a:first', RCCS.toggle.menuItem).click(function(){
  	  if (RCCS.toggle.trigger.is('.active')) {
  	    // If the toggle's already open, scroll to it.
  	    $j(window).scrollTo(RCCS.toggle.element, 800, { axis : 'y' });
  	  } else {
  	    RCCS.toggle.trigger.trigger('click');
  	  };
  	  return false;
  	});
  	// Deep-linking
    if (window.location.hash == '#' + RCCS.toggle.hash) {
      RCCS.toggle.trigger.trigger('click');
    };
	};

	// Hello Panel:
  var helloWrapper = $j('#hello-panel');
  if (helloWrapper.length) {
    var goodbye = $j('#goodbye'),
        hello = $j('#hello-panel-content'),
        helloTop = parseInt(helloWrapper.css('top').replace('px', '')),
        helloRight = parseInt(helloWrapper.css('right').replace('px', ''));
    goodbye.click(function(){
      hello.slideToggle('slow');
      $j(this).toggleClass('active');
      return false;
    });
    $j(window).scroll(function(){
      var fixPosition = $j(window).scrollTop() > helloTop;
      if (fixPosition && helloWrapper.css('position') != 'fixed') {
        var helloNewRight = $j('body').width() - helloWrapper.offset().left - helloWrapper.outerWidth();
        helloWrapper.css({position : 'fixed', top : 0, right : helloNewRight});
      }
      else if (!fixPosition && helloWrapper.css('position') == 'fixed') {
        helloWrapper.css({position : 'absolute', top : helloTop, right : helloRight});
      };
    }).trigger('scroll');
    // Show only once per session
  //	if (readCookie('hellopanel') != 'loaded') {
      hello.slideDown('slow');
      goodbye.addClass('active');
     // setTimeout(function(){
     //   hello.slideUp('slow');
     //   goodbye.removeClass('active');
     // }, 8*1000);
    //  createCookie('hellopanel','loaded','');
   // }
  };

  if (typeof ord=='undefined') { ord=Math.random()*10000000000000000; };

	if(readCookie('detectmobilesticky')) {
		$j('#mobile-link').show();
	}

	//Open links with rel attribute of 'external' in new browser window.
	//Use instead of target="_blank" to pass strict doctype validation
	$j('a[rel=external]').attr('target','_blank');

	//Scrolls back to top of page
	$j('#btn-back-to-top').click(function(){		
		$j(window).scrollTo( {top:'0',left:'0'}, 500 );
		return false;
	});	

	// Print button
	$j('.print').click(function(){
		if($j('#calendar-tickets').length) {
			if (document.createStyleSheet){
				document.createStyleSheet('/wp-content/themes/rccs/css/calendar-print-preview.css');
				var ieStyleSheetPrint = document.createStyleSheet('/wp-content/themes/rccs/css/calendar-print.css');
				ieStyleSheetPrint.media = 'print';
			}
			else {
				$j('head').append($j('<link rel="stylesheet" type="text/css" href="/wp-content/themes/rccs/css/calendar-print-preview.css" media="screen" />'));
				$j('head').append($j('<link rel="stylesheet" type="text/css" href="/wp-content/themes/rccs/css/calendar-print.css" media="print" />'));
			}	
			setTimeout ('calendarPrint()',500);  
		} else {
			window.print();
		}
		return false;
	});

	if(!$j('.page-id-60').length > 0) {
		$j('.back-home').show();
	};
});

//Seating Chart Map on NY Tickets
function seatingOpen(){ 
	newWindow('/newyork/seating.html','interactiveSeating',700,670,false,false,true);
	return false;
}

function adSection() {
	var x = window.location.href.split('://')[1].split('/');
	var f = x[1];
	if(f=="nationaltour"){
		f="national"
	}
	return f;
};

function adPage() {
	var x = window.location.href.lastIndexOf('/')+1;
	var y = window.location.href.length;
	var z = "index.html"
	if(x<y) {
		z = window.location.href.substring(x,y);
	}
	z = z.split('.')[0]
	if($j('.page-id-86, .page-id-60').length>0){
		z="homepage";
	}
	return z;
};

function calendarPrint(){
	if (o === undefined) {
      $j('body').append('<div id="print-price-preview" class="overlay"><div id="print-price-options"></div><div id="print-price-tables"></div></div>');
      var o = $j('#print-price-preview').overlay({
        api: true,
        //top: 20,
        mask: {
          color: '#000',
          loadSpeed: 200,
          opacity: 0.8
        },
        close: '#print-preview-cancel'
      });
    };
    o.load();

    if (!$j('#print-price-preview table').length) {
      // Add a header with the title, phone number and address (or email address).
      var title = document.title.replace(' - Radio City Christmas Spectacular', '');
      if (title.indexOf('Tickets') < 0 && title.indexOf('Sales') < 0) {
        title += ' Tickets';
      };
      var header = $j('<div id="print-header"><h3 id="print-title">' + title + '</h3><ul id="print-call-visit"></ul></div>');
      $j('#ticket-details div.call-visit > div').each(function(){
        $j("#print-call-visit", header).append('<li>' + $j(this).text() + '</li>');
      });
      $j('#print-price-tables').prepend(header);
      // Clone the calendar and remove the inactive dates.
      var cal = $j('#calendar-dates').clone();
      cal.find('li:has(span.inactive)').remove();
      // Get the pricing key (NOTE: we are assuming the keys do not change throughout the calendar)
      var pricingKey = [];
      // Group sales are marked up differently, so we have to check.
      var groupSales = false,
          hasPeakStatus = false,
          firstPrice = $j('div.price:first', cal);
      if ($j('h5', firstPrice).length) {
        groupSales = true;
      };
      if ($j('span.peak-status', firstPrice).length) {
        hasPeakStatus = true;
      };
      $j('dd', firstPrice).each(function(i){
        // Different pages have different pricing keys that need to be abbreviated.
        pricingKey[i] = $j(this).text()
          .replace('Orchestra / ', '')
          .replace('Orchestra/ ', '')
          .replace('Orch/', '')
          .replace('Mezzanine', 'Mezz.')
          .replace('Balcony', 'Balc')
          .replace('Pricing Level', 'Level');
      });
      var dayAbbr = {
        Sunday    : 'Sun.',
        Monday    : 'Mon.',
        Tuesday   : 'Tues.',
        Wednesday : 'Wed.',
        Thursday  : 'Thur.',
        Friday    : 'Fri.',
        Saturday  : 'Sat.'
      };
      var monthAbbr = {
        Nov : 11,
        Dec : 12,
        Jan : 1
      };
      // Loop through each month:
      var tabs = $j('#calendar-tabs a');
      $j('ol', cal).each(function(i){
        var month = $j(tabs[i]).text();
        var wrapperID = 'print-tickets-table-' + month.toLowerCase() + '-wrapper';
        var wrapper = $j('#print-price-tables').append('<div id="' + wrapperID +'"></div>').find('#' + wrapperID);
        // Add checkbox to toggle the month if there are multiple months to display
        if (tabs.length > 1) {
          wrapper.append('<h3>' + month + '</h3>');
          $j('#print-price-options').append('<div class="checkbox"><input type="checkbox" name="print-' + month.toLowerCase() + '" checked="checked" value="' + month + '" />&nbsp;' + month + '</div>');
        };
        var table = $j('<table id="print-tickets-table-' + month.toLowerCase() + '"><col /><col /><col /><col /><col /><col /><col /><col /><thead><tr><th>Date</th><th>Time</th></tr></thead><tbody></tbody></table>');
        // Add the pricing key to the table header.
        if (groupSales) {
          $j('th', table).attr('rowspan', 2);
          $j('thead tr', table).append('<th colspan="3" style="text-align:center;">Groups of 9-24</th><th colspan="3">Groups of 25 or more</th>').after('<tr></tr>');
        }
        for (var k=0; k < pricingKey.length; k++) {
          $j('thead tr:last', table).append('<th>' + pricingKey[k] + '</th>');
        };
        // Add the peak status to the table header.
        if (hasPeakStatus) {
          $j('thead tr', table).append('<th>Peak</th>');
        };
        // Loop through each time:
        $j('li div.price', this).each(function(ti){
          var dayRow = '<tr class="' + (ti % 2 ? 'even' : 'odd') + '">';
          // Split out day and time into 2 cells
          var dayTime = $j('h3', this).text().replace('Christmas Eve ', '');
          dayTime = dayTime.split(' - ');
          // Replace weekday name with abbreviated version
          var daySplit = dayTime[0].split(',');
          dayRow += '<td class="day">' + dayAbbr[daySplit[0]] + daySplit[1].replace('Nov ', '11/').replace('Dec ', '12/').replace('Jan ', '1/') + '</td>';
          dayRow += '<td class="time">' + dayTime[1] + '</td>';
          // Add a cell for each of the performances
          $j('dl.prices dt', this).each(function(){
            dayRow += '<td class="center">' + $j(this).text() + '</td>';
          });
          // Add the peak status. Use "Yes" and "No" rather than "Peak" and "Off-Peak" to make it shorter.
          if (hasPeakStatus) {
            dayRow += '<td class="center">' + ($j('span.peak-status', this).text() == 'Peak Performance' ? 'Yes' : 'No') + '</td>';
          };
          dayRow += '</tr>';
          $j('tbody', table).append(dayRow);
        });
        wrapper.append(table);
      });
      $j('#print-price-options').append('<div class="float-r"><div class="print-action"><input type="submit" value="Print" id="print-preview-done" /></div><div class="print-action"><input type="submit" value="Cancel" id="print-preview-cancel" /></div></div><div class="clear"></div>');
      $j('#print-price-options input:checkbox').change(function(){
        var month = $j(this).attr('name').replace('print-', '');
        $j('#print-tickets-table-' + month + '-wrapper').toggle();
      });
      $j('#print-preview-done').click(function(){
        window.print();
        return false;
      });
      $j('#print-preview-cancel').click(function(){
        o.close();
        return false;
      });
    };

    return false;
}

/*
$j(function(){
	//Display survey if user is on the site for more then x mnutes or has visited more than x pages.
	//Whatever comes first. Survey gets shown only once.
	if (readCookie('pageCounter') != 'already_seen') {
		//countdown in seconds
		var countdown = 300; 
		//current timestamp
		var now   = Date.parse(new Date());
		if(!readCookie('ready')) {
			createCookie('ready',Date.parse(new Date (now + countdown  * 1000)), 0);
		}
		var surveyTimer = setInterval(function() {
			var diff = (readCookie('ready') - Date.parse(new Date()));
			//console.log(diff/1000 + ' seconds left');
			if (diff <= 0) {
				surveyModal();
				clearInterval(surveyTimer);
			}
		},1000);
		
		var pageCounter = readCookie('pageCounter');
		var pageLast = readCookie('pageLast');
		var pageInt = 0;
		if(pageCounter) {
			pageInt = parseInt(pageCounter);
			//Disable page views requirement
			//if (pageInt > 3) {
			//	surveyModal();
			//}
			//if (window.location.href == pageLast) return false;
			
		}
		createCookie('pageCounter',(pageInt + 1),1);
		createCookie('pageLast',window.location.href,1);
		return false;
	}
	
});

//should supercede any existing modals
function surveyModal() {
if(!$j('#subscribe-modal').is(':visible')) {
	$j('#survey-modal').overlay({
		mask: {
			color: '#000',
			loadSpeed: 200,
			opacity: 0.8
		},
		load: true,
		onLoad: function(){
			createCookie('pageCounter','already_seen',90);
			$j('#survey-no').click(function(){
				$j('#survey-modal').overlay().close();
				return false;
			});
			$j('#survey-yes').click(function(){
				//Randomizer algorithm. not exactly split. skews towards false
				if(Math.random() * 2 > 1) {
					var surveyLink = 'http://www.insightexpress.com/s/2011195517';
				} else {
					var surveyLink = 'http://www.insightexpress.com/s/2011195517';
				}
				window.open(surveyLink)
				$j('#survey-modal').overlay().close();
				return false;
			});
		}
	});
}
}


$j(window).load(
    function() {
        if (readCookie('subscribeEmail') != 'already_seen') {
			$j('#subscribe-modal').overlay({
				top: '30%',
				mask: {
					color: '#000',
					loadSpeed: 200,
					opacity: 0.8
				},
				load: true,
				onLoad: function(){
					createCookie('subscribeEmail','already_seen',90);
				}
			});
		}
    }
);
*/
