/** Constants */

// Which page should be loaded first
kDefaultPage = "Gallery";

// An array of gallery images to load
kGalleryImages = ["images/Gallery/01.JPG", "images/Gallery/02.JPG", 
                  "images/Gallery/03.JPG", "images/Gallery/04.JPG",
                  "images/Gallery/05.JPG", "images/Gallery/06.JPG",
                  "images/Gallery/07.JPG", "images/Gallery/08.JPG",
                  "images/Gallery/09.JPG", "images/Gallery/10.JPG",
                  
                  "images/Gallery/11.JPG", "images/Gallery/12.JPG",
                  "images/Gallery/13.JPG", "images/Gallery/14.JPG",
                  "images/Gallery/15.JPG", "images/Gallery/16.JPG",
                  "images/Gallery/17.JPG", "images/Gallery/18.JPG",
                  "images/Gallery/19.JPG", "images/Gallery/20.JPG",
                  
                  "images/Gallery/21.JPG", "images/Gallery/22.JPG",
                  "images/Gallery/23.JPG", "images/Gallery/24.JPG",
                  "images/Gallery/25.JPG", "images/Gallery/26.JPG",
                  "images/Gallery/27.JPG", "images/Gallery/28.JPG",
                  "images/Gallery/29.JPG", "images/Gallery/30.JPG",
                  
                  "images/Gallery/31.JPG", "images/Gallery/32.JPG",
                  "images/Gallery/33.JPG", "images/Gallery/34.JPG",
                  "images/Gallery/35.JPG", "images/Gallery/36.JPG",
                  "images/Gallery/37.JPG", "images/Gallery/38.JPG",
                  "images/Gallery/39.JPG", "images/Gallery/40.JPG",
                  
                  "images/Gallery/41.JPG", "images/Gallery/42.JPG",
                  "images/Gallery/43.JPG", "images/Gallery/44.JPG",
                  "images/Gallery/45.JPG", "images/Gallery/46.JPG",
                  "images/Gallery/47.JPG", "images/Gallery/48.JPG",
                  "images/Gallery/49.JPG", "images/Gallery/50.JPG",
                  
                  "images/Gallery/51.JPG", "images/Gallery/52.JPG",
                  "images/Gallery/53.JPG", "images/Gallery/54.JPG",
                  "images/Gallery/55.JPG", "images/Gallery/56.JPG",
                  "images/Gallery/57.JPG", "images/Gallery/58.JPG",
                  "images/Gallery/59.JPG", "images/Gallery/60.JPG",
                  
                  "images/Gallery/61.JPG", "images/Gallery/62.JPG",
                  "images/Gallery/63.JPG", "images/Gallery/64.JPG",
                  "images/Gallery/65.JPG", "images/Gallery/66.JPG",
                  "images/Gallery/67.JPG", "images/Gallery/68.JPG",
                  "images/Gallery/69.JPG", "images/Gallery/70.JPG",
                  
                  "images/Gallery/71.JPG", "images/Gallery/72.JPG",
                  "images/Gallery/73.JPG", "images/Gallery/74.JPG",
                  "images/Gallery/75.JPG", "images/Gallery/76.JPG",
                  "images/Gallery/77.JPG", "images/Gallery/78.JPG",
                  "images/Gallery/79.JPG", "images/Gallery/80.JPG",
                  
                  "images/Gallery/81.JPG", "images/Gallery/82.JPG"

                 ];

kTransparentPng = "images/x.png";

kPages = {   
             Gallery: {primary:"gallery", secondary:null, anchor:"Gallery"},
             About:   {primary:"about", secondary:null, anchor:"About"},
             Contact: {primary:"contact", secondary:null, anchor:"Contact"},
             Details: {primary:"details", secondary:"rates", anchor:"Details"},
             Services: {primary:"details", secondary:"rates", anchor:"Rates"},
             Locations: {primary:"details", secondary:"locations", anchor:"Locations"},
             FAQ: {primary:"details", secondary:"faq", anchor:"FAQ"},
         }

gVisitedPages = [];
gVisitStartTime = (new Date()).getTime();

/** Dyname Globals */
gGalleryIndex = -1;
gSlideshowActive = true;

/** Support (jQuery Plugins) */
(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = 0; i < args_len; ++i) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery);

(function ($) {
    $.fn.vCenter = function(container) {
        return this.each(function(i){
	   if(container == null) {
	      container = 'div';
	   }
	   var paddingPx = 10; //change this value as you need (It is the extra height for the parent element)
	   $(this).html("<" + container + ">" + $(this).html() + "</" + container + ">");
	   var el = $(this).children(container + ":first");
	   var elh = $(el).height(); //new element height
	   var ph = $(this).height(); //parent height
	   if(elh > ph) { //if new element height is larger apply this to parent
	      return;
//	       $(this).height(elh + paddingPx);
//	       ph = elh + paddingPx;
	   }
	   var nh = (ph - elh) / 2; //new margin to apply
	   $(el).css('margin-top', nh);
        });
     };
})(jQuery);

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        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(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        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;
    }
};

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

/** Document Ready */
$(document).ready(function() 
{
       
    // Assign click handler to each menuitem
    $('a').click(function(){ 
       if (this.href.indexOf('#')+1)
       {
          page = getPage(this.href.substr(this.href.indexOf('#')+1))
          showPage(page);
       }
    });  
    
    $('#galleryNext').click(function()
      {
         gSlideshowActive = false;
         nextGalleryImage();
         return false;
      } );

    $('#galleryPrevious').click(function()
      {
         gSlideshowActive = false;
         previousGalleryImage();
         return false;
      } );
          
    if (!$.cookie('firstReferrer'))
    {
       $.cookie('firstReferrer', document.referrer);
    }
    visitCount = Number($.cookie('visitCount')) + 1;
    $.cookie('visitCount', visitCount);
    
    $("#autismGalleryLink").click( function() {alert("Hi!")});
    
    $(".menuitem").hover(onEnterMenuitem, onExitMenuitem);
    $(".menuitem").wrap('<div class="menuitemContainer"></div>');
    $(".menuitem").parent().prepend('<div class="menuLeft"></div>');
    $(".menuitem").parent().append('<div class="menuRight"></div>');
    $(".menuitem").addClass("menuCenter");
    $("#header").append('<div style="clear:both"></div>');
    
    $(".submenuitem").parent().after('<div style="clear:both"></div>');
    //alert( $("a[rel='autismGallery']").colorbox() );

    // Start preloading images
    jQuery.preLoadImages.apply(null,kGalleryImages);
    
    //Show initial page
    var initialPage = getPage();
    showPage(initialPage);
});

function onEnterMenuitem()
{
   $(this).parent().addClass("hover");
}

function onExitMenuitem()
{
   $(this).parent().removeClass("hover");
}

function getPage(anchor)
{
   if (!anchor)
   {
      //Use the active anchor, if one isn't being provided
      anchor = window.location.hash ? window.location.hash.substr(1) : null;
   }
   
   page = kPages[anchor] ? kPages[anchor] : kPages[kDefaultPage];
   return page;
}

function setPage(page)
{
   window.location.href = "#" + page.anchor;
   gVisitedPages.push(page.anchor);
   var pageTracker = _gat._getTracker("UA-295205-3");
   pageTracker._trackPageview("/" + page.anchor);

   $(".menuitemContainer").removeClass("active");
   $("#mi" + page.primary).parent().addClass("active");
   $("#mi" + page.secondary).parent().addClass("active");
}

function showPage(page)
{
   oldPage = $("content").data("page");

   transitionPage(page);
   setPage(page)
   if (page.anchor == "Gallery")
   {
      showGalleryControls(true);
      if (oldPage != page)
      {
         //We just got here, start up the gallery
         gSlideshowActive = true;
         nextGalleryImage();
      }
   }
   else
   {
      showGalleryControls(false);
      gSlideshowActive = false;
   }
}

function showGalleryControls(enable)
{
   if (enable)
   {
      $("#galleryNext").appendTo($('.colLogo'));
      $("#galleryPrevious").appendTo($('.colLogo'));
   }
   else
   {
      $("#galleryNext").appendTo($('#gallery'));
      $("#galleryPrevious").appendTo($('#gallery'));
   }
}

function setGalleryImage(url, tickInterval)
{
   if (!gSlideshowActive)
   {
      //Manual switch, just change the image without FX
      $(".colGal").css("backgroundImage","url("+url+")");
   }
   //Get the current image.
   var current = $(".colGal").css("backgroundImage").replace(/^url|[()]/g, '');

   if (current && current != "none")
   {
      //Promote it to the front img 
      $(".galImageFront").attr('src',current);
      $(".galImageFront").show();
   }
   
   //Set the background image
   $(".colGal").css("backgroundImage","url("+url+")");
   
   // If slideshow, fade out the front image
   $(".galImageFront").stop().fadeOut( 
      1000, 
      function() 
      {
         if (gSlideshowActive && tickInterval > 0)
         {
            window.setTimeout(onSlideshowTick, tickInterval);
         }
      }
   );
}

function onSlideshowTick()
{
   if (gSlideshowActive)
   {
      nextGalleryImage();
   }
}

function nextGalleryImage()
{
   ++gGalleryIndex;
   if (gGalleryIndex >= kGalleryImages.length)
   {
      gGalleryIndex = 0;
   }
   setGalleryImage(kGalleryImages[gGalleryIndex],gSlideshowActive ? 6000 : -1);      
}

function previousGalleryImage()
{
   --gGalleryIndex;
   if (gGalleryIndex < 0)
   {
      gGalleryIndex = kGalleryImages.length-1;
   }
   setGalleryImage(kGalleryImages[gGalleryIndex], -1);
}


function sendContactForm()
{
   var payload = {};
   payload.name = $("#contactName").val();
   payload.email = $("#contactEmail").val();
   payload.phone = $("#contactPhone").val();
   payload.message = $("#contactMessage").val();
   payload.weddingInfo = $("#contactWeddingInfo").val()
   payload.visitCount = Number($.cookie('visitCount'));
   visitLengthMs = (new Date()).getTime() - gVisitStartTime;
   visitLengthMinutes =  Math.floor(visitLengthMs/60/1000);
   visitLengthSeconds = Math.round((visitLengthMs - (visitLengthMinutes*60*1000))/1000);
   payload.visitLength = visitLengthMinutes + ":" + visitLengthSeconds + "(mm:ss)";
   payload.firstVisit = $.cookie('firstVisit') ? $.cookie('firstVisit') : "[Unknown]";
   payload.firstReferrer = $.cookie('firstReferrer') ? $.cookie('firstReferrer') : "[Unknown]";
   payload.currentReferrer = document.referrer ? document.referrer : "[Direct]";
   payload.userAgent = BrowserDetect.browser + " " + BrowserDetect.version + " on " + BrowserDetect.OS;
   payload.visitedPages = gVisitedPages.join(',');
   
   if (!payload.name || !payload.email || !payload.message)
   {
      alert("You must supply your name, email address, and a message in order to use this form.");
      return;
   }
   
   $.post("contact.php", payload, function(data)
      {
         //Save as a token transaction
         var _gaq = _gaq || [];
           _gaq.push(['_setAccount', 'UA-295205-3']);
           _gaq.push(['_trackPageview']);
           
           orderNumber = Math.floor(Math.random()*10000+1);
           _gaq.push(['_addTrans',
             orderNumber + '',           // order ID - required
             'JVPWeddings',  // affiliation or store name
             '1.0',          // total - required
             '0',           // tax
             '0',              // shipping
             '',       // city
             '',     // state or province
             ''             // country
           ]);

            // add item might be called for every item in the shopping cart
            // where your ecommerce engine loops through each item in the cart and
            // prints out _addItem for each
           _gaq.push(['_addItem',
             orderNumber + '',           // order ID - required
             'CFS',           // SKU/code - required
             'Contat Form Submission',        // product name
             '',   // category or variation
             '1',          // unit price - required
             '1'               // quantity - required
           ]);
           _gaq.push(['_trackTrans']); //submits transaction to the Analytics servers
         
         alert("Your message is on its way.  Thank you!");
      });
}

function transitionPage(page)
{
   oldPage = $("#content").data("page");
         
   if (!page.primary)
   {
      return;
   }
   var content = $("#" + page.primary);
   
   if (content.length == 0)
   {
      //Do nothing if we can't identify the new page.
      return;
   }

   if (page.secondary && page.primary == "details")
   {
      //It is details content.
      
      //Replace content in details column 1
      if (oldPage && oldPage.secondary)
      {
         //Move current subcontent back where it came from
         $(".detailsCol1").children().appendTo($("#"+oldPage.secondary));
      }
      //Move new subcontent into visible column
      $("#" + page.secondary).children().appendTo($(".detailsCol1"));


   }

   $(".col1").vCenter();
   $("#content").data("page",page);
   $("a[rel='autismGallery']").colorbox({rel:'autismGallery',slideshow:true,transition:"fade"});

    $('#contactSubmit').click(function()
      {
         
         sendContactForm();
         return false;
      }
    );
   
   if (oldPage && page.primary == oldPage.primary)
   {
      //Already on correct page; do nothing.
      return;
   }
   
   $("#content").fadeOut("fast", function() {
      

      if (oldPage && oldPage.primary)
      {
         if (oldPage.primary == "details")
         {
            //Move current subcontent back where it came from
            $(".detailsCol1").children().appendTo($("#"+oldPage.secondary));
         }            
         //Move current content back where it came from
         $("#content").children(".column").appendTo($("#"+oldPage.primary));         
      }
      
      //Move new content into visible content div
      content.children(".column").appendTo($("#content"));

      $("#content").fadeIn("fast");
      $(".col1").vCenter();
      $("a[rel='autismGallery']").colorbox({rel:'autismGallery',slideshow:true,transition:"elastic"});
    $('#contactSubmit').click(function()
      {
         
         sendContactForm();
         return false;
      }
    );
   });
}
