/*
var isInIFrame = (window.location != window.parent.location) ? true : false;
if (isInIFrame) {
  //alert ("FRAME");
}

if (top === self || !isInIFrame)
{
  //not in a frame
}
else
{
  window.parent.location = window.location;
}
*/
$(document).ready(function(){

    // Exit pop-up detection injection
    $('body').prepend('<div id="exiting" style="width:100%; height:20px; background-color:#fff;"></div>');
    
    // Detect if phone lead via presence of Pub cookie
    if($.cookie('Pub')) {
        // push alternate phone number into wrapper
        $('.headerPhone').html("866.559.7946 <span class='headerText'>8am-9pm EST Mon-Fri</span>");
    }

    /* Suppress Exit Overlay    
    // Arm exit overlay
    $("#exitOverlay").overlay({mask: '#fff',speed: "fast"});
    
    // Fire overlay on exit detection    
    if($.cookie('exited') || $.cookie('IK') == 'yes' || $.cookie('IdeaKitRequested') == 'yes'){
        // Has seen exit pop-up    
    } else {
        $('#exiting').mouseenter(function(){
            $('#exitOverlay').overlay().load();
            //$.cookie('exited','yes',{expires:0});
            $.cookie('exited','yes');
            $('#exiting').unbind('mouseenter');
            $('#exiting').unbind();              
        });
    
    };
    
    $('#submitExit').mousedown(function(){
        if($('.f_fname') !='' && $('.f_lname') != '' && $('.f_email') != '' ){
            $('#exitOverlay').overlay().close();            
        }
    })    
    */
    
	// Find a pool submit Zip
	$('.submitZip').click(function(){ window.location = "find-a-pool.php?z="+$("#zip").val()+""; });
	$('.submitZip2').click(function(){ window.location = "find-a-pool.php?z="+$("#zip2").val()+""; });
	$("#zip").keyup(function(event){
	  if(event.keyCode == 13){
		$("#submitZip").click();
	  }
	});
	$("#zip2").keyup(function(event){
	  if(event.keyCode == 13){
		$("#submitZip2").click();
	  }
	});

	// Products Page
	$('.pItem:eq(0)').not('.exclude').click(function(){ window.location = 'endless-pool.php'; })
	$('.pItem:eq(1)').not('.exclude').click(function(){ window.location = 'waterwell.php'; })	
	$('.pItem:eq(2)').not('.exclude').click(function(){ window.location = 'swim-spa.php'; })
	$('.pItem:eq(3)').not('.exclude').click(function(){ window.location = 'fastlane.php'; })	
	$('.pItem:eq(4)').not('.exclude').click(function(){ window.location = 'fastlane-pool.php'; })
	$('.pItem:eq(5)').not('.exclude').click(function(){ window.location = 'fiberglass-pool.php'; })	
	
	// Uses Page
	$('.uItem:eq(0)').not('.exclude').click(function(){ window.location = 'uses-swimming-overview.php'; })
	$('.uItem:eq(1)').not('.exclude').click(function(){ window.location = 'water-exercise-pools.php'; })	
	$('.uItem:eq(2)').not('.exclude').click(function(){ window.location = 'aquatic-therapy-pools.php'; })
	$('.uItem:eq(3)').not('.exclude').click(function(){ window.location = 'swim-training-pools.php'; })	
	$('.uItem:eq(4)').not('.exclude').click(function(){ window.location = 'uses-fun-and-relaxation-overview.php'; })
	$('.uItem:eq(5)').not('.exclude').click(function(){ window.location = 'open-water-swimming-pools.php'; })	

	// Commercial Products Page
	$('.commProductItem:eq(0)').not('.exclude').click(function(){ window.location = 'endless-pool.php'; })
	$('.commProductItem:eq(1)').not('.exclude').click(function(){ window.location = 'fiberglass-pool.php'; })	
	$('.commProductItem:eq(2)').not('.exclude').click(function(){ window.location = 'endless-pool-elite.php'; })
	$('.commProductItem:eq(3)').not('.exclude').click(function(){ window.location = 'waterwell.php'; })	
	$('.commProductItem:eq(4)').not('.exclude').click(function(){ window.location = 'underwater-treadmill.php'; })
	$('.commProductItem:eq(5)').not('.exclude').click(function(){ window.location = 'endless-pool-dual-propulsion.php'; })	


	
	$("#primaryNav a:not('.prod'), .primaryNavLid").mouseover(function(){
		$('#flyout').slideUp(200);
		$('.prod').removeClass('prodActive');
	})
	
	
	$(".pItem, .commProductItem").hover(function() {  
		$(this).addClass('pItemOver');
		},function() { 
		$(this).removeClass('pItemOver'); 
	}); 


	$(".uItem").hover(function() {  
		$(this).addClass('uItemOver');
		},function() { 
		$(this).removeClass('uItemOver'); 
	}); 

	// Clear zip input
	$("#zip, #zip2").focus(function() {
		if( this.value == this.defaultValue ) {
			this.value = "";
		}
	}).blur(function() {
		if( !this.value.length ) {
			this.value = this.defaultValue;
		}
	});
	
	imagePreview();	
// END DOC READY	 	
});

// Yard Tour
this.imagePreview = function(){	
		xOffset = 175;
		yOffset = -115;
	$("a.preview").hover(function(e){
		this.t = this.title;
		this.title = "";	
		var c = (this.t != "") ? "<br/>" + this.t : "";
		$("body").append("<p id='preview'><img src='"+ this.href +"' alt='Image preview' />"+ c +"</p>");								 
		$("#preview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");						
    },
	function(){
		this.title = this.t;	
		$("#preview").remove();
    });	
	$("a.preview").mousemove(function(e){
		$("#preview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});			
};


// Helpers & Plug-ins ////////////////////////////
// Fetch url param
$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});	

// Manage Cookies
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') {
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString();
        }
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

	// Form management
	function getForm(){
		var formParameter = $.getUrlVar('form');
		switch ($.getUrlVar('form')) {
			case '28043': 	
				// Try A Pool Near You
				$('.rfiTitle').html('Try A Pool Near You');
				$('#formContent').load('inc/form-content.php #28043', 
					function(){
						$('#subBtn').attr('value','Find a Demonstration Pool Near Me');	
						//alert('TRY A POOL');
					});
				break;
				
			case '28042': // Email Signup
				$('.rfiTitle').html('Email Signup');
				$('#formContent').load('inc/form-content.php #28042', function(){$('#subBtn').attr('value','Sign Up')});
				break;					  
			case '28044': // Endless Pool Planning Guide
				$('.rfiTitle').html('Endless Pool Planning Guide');
				$('#formContent').load('inc/form-content.php #28044', function(){$('#subBtn').attr('value','Download Our Planning Guide')});
				break;
			case '28045': // Swim Spa Planning Guide
				$('.rfiTitle').html('Swim Spa Planning Guide');
				$('#formContent').load('inc/form-content.php #28045', function(){$('#subBtn').attr('value','Download Our Planning Guide')});
				break;
			case '28046': // Fastlane Planning Guide
				$('.rfiTitle').html('Fastlane Planning Guide');
				$('#formContent').load('inc/form-content.php #28046', function(){$('#subBtn').attr('value','Download Our Planning Guide')});
				break;
			case '28047': // Fiberglass Pool Planning Guide
				$('.rfiTitle').html('Fiberglass Pool Planning Guide');
				$('#formContent').load('inc/form-content.php #28047', function(){$('#subBtn').attr('value','Download Our Planning Guide')});
				break;
			case '28048': // WaterWell Planning Guide
				$('.rfiTitle').html('WaterWell Planning Guide');
				$('#formContent').load('inc/form-content.php #28048', function(){$('#subBtn').attr('value','Download Our Planning Guide')});
				break;
			case '28050': // Fastlane Pool Planning Guide
				$('.rfiTitle').html('Fastlane Pool Planning Guide');
				$('#formContent').load('inc/form-content.php #28050', function(){$('#subBtn').attr('value','Download Our Planning Guide')});
				break;
			
			case '28052': // Endless Pool Pricing
				$('.rfiTitle').html('Endless Pool Pricing');
				$('#formContent').load('inc/form-content.php #28052', function(){$('#subBtn').attr('value','Send')});
				break;
			
			case '28053': // Swim Spa Pricing
				$('.rfiTitle').html('Swim Spa Pricing');
				$('#formContent').load('inc/form-content.php #28053', function(){$('#subBtn').attr('value','Send')});
				break;
			
			case '28054': // Fastlane Pricing
				$('.rfiTitle').html('Fastlane Pool Pricing');
				$('#formContent').load('inc/form-content.php #28054', function(){$('#subBtn').attr('value','Send')});
				break;
			
			case '28055': // Fastlane Pool Pricing
				$('.rfiTitle').html('Fastlane Pool Pricing');
				$('#formContent').load('inc/form-content.php #28055', function(){$('#subBtn').attr('value','Send')});
				break;
			
			case '28056': // Fiberglass Pool Pricing
				$('.rfiTitle').html('Fiberglass Pool Pricing');
				$('#formContent').load('inc/form-content.php #28056', function(){$('#subBtn').attr('value','Send')});
				break;					  					  
			
			case '28057': // Waterwell Pricing
			    $.cookie('IK','yes',{expires:0});
				$('.rfiTitle').html('WaterWell Pricing');
				$('#formContent').load('inc/form-content.php #28057', function(){$('#subBtn').attr('value','Send')});
				break;
			
			case '0': // ...
				$('#formContent').load('inc/form-content.php #OUTRO', function(){$('#subBtn').attr('value','Send')});
				break;					  					  
			
			
			default:
			// assume 28041
			// nada yet
		}    		
	}	
	
	function getFileNameFromLocation() {
		var currentLocation = location.href;
		var currentFileName = '';
		currentLocation = currentLocation.split('#');
		currentLocation = currentLocation[0];
		currentLocation = currentLocation.split('?');
		currentLocation = currentLocation[0];
		currentLocation = currentLocation.split('/');
		
		currentFileName = currentLocation.slice(-1);
		return currentFileName;
	}
	
	function getPathFromLocation(currentFileName) {
		var myPath = location.pathname.split(currentFileName);
		myPath = myPath[0];
		return myPath;
	}
	
$.extend({URLEncode:function(c){var o='';var x=0;c=c.toString();var r=/(^[a-zA-Z0-9_.]*)/;
  while(x<c.length){var m=r.exec(c.substr(x));
    if(m!=null && m.length>1 && m[1]!=''){o+=m[1];x+=m[1].length;
    }else{if(c[x]==' ')o+='+';else{var d=c.charCodeAt(x);var h=d.toString(16);
    o+='%'+(h.length<2?'0':'')+h.toUpperCase();}x++;}}return o;},
URLDecode:function(s){var o=s;var binVal,t;var r=/(%[^%]{2})/;
  while((m=r.exec(o))!=null && m.length>1 && m[1]!=''){b=parseInt(m[1].substr(1),16);
  t=String.fromCharCode(b);o=o.replace(m[1],t);}return o;}
});

	
	
$.fn.accordion = function() {
  return this.each(function() {
    $container = $(this);

    // Hijack handles.
    $container.find("h2").each(function() {
      var $header = $(this);
      var $selected = $header.next();

    $header
        .click(function() {  
          if ($selected.is(":visible")) {
            $selected
              .animate({ height: 0 }, { duration: 200, complete: function() {
                $(this).hide();
              }
            });
          } else {
            $unselected = $container.find("p:visible");
            $selected.show();
            var newHeight = heights[$selected.attr("id")];
			// $header.addClass('fLight');
			$('.acco h2').not(this).addClass('fLight');
			$('.acco h2').not(this).removeClass('fSelected');
			$(this).removeClass('fLight');
			$(this).addClass('fSelected');
            var oldHeight = heights[$unselected.attr("id")];

            $('<div>').animate({ height : 1 }, {
              duration  : 200, 
              step      : function(now) {
                var stepSelectedHeight = Math.round(newHeight * now);
                $selected.height(stepSelectedHeight);
                $unselected.height(oldHeight + Math.round((newHeight - oldHeight) * now) - Math.round(newHeight * now));
              },
              complete  : function() {
                $unselected
                  .hide()
                  .css({ height : 0 });
                }
            });
          }
          return false;
        });
    });

    // Iterate over panels, save heights, hide all.
    var heights = new Object();
    $container.find("p").each(function() {

      $this = $(this);
      $this.css("overflow", "hidden");
      heights[$this.attr("id")] = $this.height();
      $this
        .hide()
        .css({ height : 0 });
    });
  });
};


//siteSettings to allow dynamic form setup.
//there are some other things in here too, hopefully for use on multiple sites
//like phone number and address and email
var siteSettings = new Array();  //set up defaults
siteSettings['demographic_form_method'] = 'ajax';
siteSettings['demographic_goton'] = '';
siteSettings['extra_form_method'] = 'normal';
siteSettings['extra_goton'] = '/';
siteSettings['default_country'] = 'USA';
siteSettings['extra_followup'] = function() { }; // empty function placeholder to prevent errors

siteSettings.extra_followup = function() {
		if (typeof destination != "undefined") {
				window.location = destination;
		}
};
siteSettings['show_f3'] = true;
