/* Common javascript functions */


/*
 * Superfish v1.4.8 - jQuery menu widget
 * Copyright (c) 2008 Joel Birch
 *
 * Dual licensed under the MIT and GPL licenses:
 * 	http://www.opensource.org/licenses/mit-license.php
 * 	http://www.gnu.org/licenses/gpl.html
 *
 * CHANGELOG: http://users.tpg.com.au/j_birch/plugins/superfish/changelog.txt
 */

(function($){
	/* hoverIntent by Brian Cherne */
	$.fn.hoverIntent = function(f,g) {
		// default configuration options
		var cfg = {
			sensitivity: 7,
			interval: 100,
			timeout: 0
		};
		// override configuration options with user supplied object
		cfg = $.extend(cfg, g ? { over: f, out: g } : f );

		// instantiate variables
		// cX, cY = current X and Y position of mouse, updated by mousemove event
		// pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
		var cX, cY, pX, pY;

		// A private function for getting mouse position
		var track = function(ev) {
			cX = ev.pageX;
			cY = ev.pageY;
		};

		// A private function for comparing current and previous mouse position
		var compare = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			// compare mouse positions to see if they've crossed the threshold
			if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
				$(ob).unbind("mousemove",track);
				// set hoverIntent state to true (so mouseOut can be called)
				ob.hoverIntent_s = 1;
				return cfg.over.apply(ob,[ev]);
			} else {
				// set previous coordinates for next time
				pX = cX; pY = cY;
				// use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
				ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
			}
		};

		// A private function for delaying the mouseOut function
		var delay = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			ob.hoverIntent_s = 0;
			return cfg.out.apply(ob,[ev]);
		};

		// A private function for handling mouse 'hovering'
		var handleHover = function(e) {
			// next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut
			var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
			while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } }
			if ( p == this ) { return false; }

			// copy objects to be passed into t (required for event object to be passed in IE)
			var ev = jQuery.extend({},e);
			var ob = this;

			// cancel hoverIntent timer if it exists
			if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

			// else e.type == "onmouseover"
			if (e.type == "mouseover") {
				// set "previous" X and Y position based on initial entry point
				pX = ev.pageX; pY = ev.pageY;
				// update "current" X and Y position based on mousemove
				$(ob).bind("mousemove",track);
				// start polling interval (self-calling timeout) to compare mouse coordinates over time
				if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}

			// else e.type == "onmouseout"
			} else {
				// unbind expensive mousemove event
				$(ob).unbind("mousemove",track);
				// if hoverIntent state is true, then call the mouseOut function after the specified delay
				if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
			}
		};

		// bind the function to the two event listeners
		return this.mouseover(handleHover).mouseout(handleHover);
	};
	$.fn.superfish = function(op){

		var sf = $.fn.superfish,
			c = sf.c,
			$arrow = $(['<span class="',c.arrowClass,'"> &#187;</span>'].join('')),
			over = function(){
				var $$ = $(this), menu = getMenu($$);
				clearTimeout(menu.sfTimer);
				$$.showSuperfishUl().siblings().hideSuperfishUl();
			},
			out = function(){
				var $$ = $(this), menu = getMenu($$), o = sf.op;
				clearTimeout(menu.sfTimer);
				menu.sfTimer=setTimeout(function(){
					o.retainPath=($.inArray($$[0],o.$path)>-1);
					$$.hideSuperfishUl();
					if (o.$path.length && $$.parents(['li.',o.hoverClass].join('')).length<1){over.call(o.$path);}
				},o.delay);	
			},
			getMenu = function($menu){
				var menu = $menu.parents(['ul.',c.menuClass,':first'].join(''))[0];
				sf.op = sf.o[menu.serial];
				return menu;
			},
			addArrow = function($a){ $a.addClass(c.anchorClass).append($arrow.clone()); };
			
		return this.each(function() {
			var s = this.serial = sf.o.length;
			var o = $.extend({},sf.defaults,op);
			o.$path = $('li.'+o.pathClass,this).slice(0,o.pathLevels).each(function(){
				$(this).addClass([o.hoverClass,c.bcClass].join(' '))
					.filter('li:has(ul)').removeClass(o.pathClass);
			});
			sf.o[s] = sf.op = o;
			
			$('li:has(ul)',this)[($.fn.hoverIntent && !o.disableHI) ? 'hoverIntent' : 'hover'](over,out).each(function() {
				if (o.autoArrows) addArrow( $('>a:first-child',this) );
			})
			.not('.'+c.bcClass)
				.hideSuperfishUl();
			
			var $a = $('a',this);
			$a.each(function(i){
				var $li = $a.eq(i).parents('li');
				$a.eq(i).focus(function(){over.call($li);}).blur(function(){out.call($li);});
			});
			o.onInit.call(this);
			
		}).each(function() {
			var menuClasses = [c.menuClass];
			if (sf.op.dropShadows  && !($.browser.msie && $.browser.version < 7)) menuClasses.push(c.shadowClass);
			$(this).addClass(menuClasses.join(' '));
		});
	};

	var sf = $.fn.superfish;
	sf.o = [];
	sf.op = {};
	sf.IE7fix = function(){
		var o = sf.op;
		if ($.browser.msie && $.browser.version > 6 && o.dropShadows && o.animation.opacity!=undefined)
			this.toggleClass(sf.c.shadowClass+'-off');
		};
	sf.c = {
		bcClass     : 'sf-breadcrumb',
		menuClass   : 'sf-js-enabled',
		anchorClass : 'sf-with-ul',
		arrowClass  : 'sf-sub-indicator',
		shadowClass : 'sf-shadow'
	};
	sf.defaults = {
		hoverClass	: 'sfHover',
		pathClass	: 'overideThisToUse',
		pathLevels	: 1,
		delay		: 800,
		animation	: {opacity:'show'},
		speed		: 'normal',
		autoArrows	: true,
		dropShadows : true,
		disableHI	: false,		// true disables hoverIntent detection
		onInit		: function(){}, // callback functions
		onBeforeShow: function(){},
		onShow		: function(){},
		onHide		: function(){}
	};
	$.fn.extend({
		hideSuperfishUl : function(){
			var o = sf.op,
				not = (o.retainPath===true) ? o.$path : '';
			o.retainPath = false;
			var $ul = $(['li.',o.hoverClass].join(''),this).add(this).not(not).removeClass(o.hoverClass)
					.find('>ul').hide().css('visibility','hidden');
			o.onHide.call($ul);
			return this;
		},
		showSuperfishUl : function(){
			var o = sf.op,
				sh = sf.c.shadowClass+'-off',
				$ul = this.addClass(o.hoverClass)
					.find('>ul:hidden').css('visibility','visible');
			sf.IE7fix.call($ul);
			o.onBeforeShow.call($ul);
			$ul.animate(o.animation,o.speed,function(){ sf.IE7fix.call($ul); o.onShow.call($ul); });
			return this;
		}
	});

})(jQuery);

// When the page is ready
$(document).ready(function(){
  // handle dropdown menus
  $('ul#nav').superfish(
    { 
      delay: 800,
      speed: 'fast',
      autoArrows:  false,                          
      dropShadows: false                           
    }
  );

  // colorbox (http://colorpowered.com/colorbox/)
  $("a.colorbox").colorbox();
  $("a.gallery_photo-link").colorbox({rel:'photo_gallery', photo:true});
    // group inline photo gallery
  $("a.inline_photo_gallery-link").each(function(i) {
    $(this).siblings("a.photo-link").attr("rel", 'group'+i);
    $(this).siblings("a.photo-link").html("");
    $(this).siblings("a.photo-link:first").html($(this).html());
    $(this).hide();
    $("a.photo-link[rel='group"+i+"']").colorbox({photo:true, speed:200});
  });
    // single colorbox views
  $("a.colorbox-mov").each(function(i) {
    $(this).colorbox({iframe:true, speed:200, preloading:false, width:800, height:800});
  });


// collapse.js
   // add global controls
   $('.global-collapsible-controls').prepend("<a class='global_collapse_hide' href=''><span>Hide All</span></a> <a class='global_collapse_show' href=''><span>Show All</span></a>");

   // hide all collapse_hide_area and add toggle button for each
   $('.collapsible .collapse_hide_area').hide();
   $('.collapsible .collapse_show_area').prepend("<div class='wrapper-toggle'><a class='collapse_toggle' href=''><span>toggle</span></a></div>");
   $('.collapsible .collapse_show_button').prepend("<a class='collapse_toggle' href=''><span>toggle</span></a>");

  // show collapse_hide_area that have show class and sync button
   $('.collapsible .collapse_hide_area.show').show();
   $('.collapsible .collapse_hide_area.show').parents(".collapsible").find("a.collapse_toggle").toggleClass('collapse_open');

  // handle click events
   $(".collapsible .collapse_toggle").click(function(event){
     $(this).parents(".collapsible").find("a.collapse_toggle").toggleClass('collapse_open');
     $(this).parents(".collapsible").children(".collapse_hide_area").toggle();
     
     // Stop the link click from doing its normal thing
     return false;
   });

  // collapse global
   $(".global_collapse_hide").click(function(event){
     $("a.collapse_toggle").removeClass('collapse_open');
     $(".collapsible .collapse_hide_area").hide();
     
     // Stop the link click from doing its normal thing
     return false;
   });
   $(".global_collapse_show").click(function(event){
     $("a.collapse_toggle").addClass('collapse_open');
     $(".collapsible .collapse_hide_area").show();
     
     // Stop the link click from doing its normal thing
     return false;
   });

// homepage cycle promo
// docs at: http://jquery.malsup.com/cycle/

  $("div#hp-page #large_promo-slides").cycle({
    fx: 'fade',
    speed: 400,    // Default FX speed ('fast' is 200)
    timeout: 8000, // 0 prevents auto cycling; 8000 -> 8 seconds, or thereabouts
    pager: '#large_promo-nav',
    pagerAnchorBuilder: function(idx, slide) {
      // return selector string for existing anchor
      return '#large_promo-nav li:eq(' + idx + ')  a';
    }
  });
  /*$("div#hp-page #description-bar").cycle({
    fx: 'fade',
    speed: 400,    // Default FX speed ('fast' is 200)
    timeout: 8000, // 0 prevents auto cycling; 8000 -> 8 seconds, or thereabouts
	cleartype: false, // fixes background problem in IE
    pager: '#description-bar',
    pagerAnchorBuilder: function(idx, slide) {
      // return selector string for existing anchor
      return '#description-bar span:eq(' + idx + ')';
    }
  });*/
  $("div#promos_minime #minime_promo_slides").cycle({
    fx: 'fade',
    speed: 400,    // Default FX speed ('fast' is 200)
    timeout: 8000, // 0 prevents auto cycling; 8000 -> 8 seconds, or thereabouts
	cleartype: false, // fixes background problem in IE
    pager: '#promos_minime_nav',
    pagerAnchorBuilder: function(idx, slide) {
      // return selector string for existing anchor
      return '#promos_minime_nav li:eq(' + idx + ')';
    }
  });
  // handle play/pause control
  $("div#hp-page ul#large_promo-nav").after(" <div id='play_pause-controls'> <span id='pause-button'><em>pause</em></span> </div> ");
  $("div#play_pause-controls span").toggle(function() {
    $(this).attr('id', 'play-button').html('<em>play</em>');
    $("div#hp-page #large_promo-slides").cycle('pause');
    $("div#hp-page #description-bar").cycle('pause');
  },
  function() {
    $(this).attr('id', 'pause-button').html('<em>pause</em>');
    $("div#hp-page #large_promo-slides").cycle('resume');
    $("div#hp-page #description-bar").cycle('resume');
  });


  // homepage scrolling banner
  function get_width_of_banner_text() {
    $("#alert-banner span").clone().appendTo("body").addClass("no_wrap");
    var w = $("body > span.no_wrap").width();
    $("body > span.no_wrap").remove();
    return w;
  }
  var w = get_width_of_banner_text();

  var max_w = $("#alert-banner").width();
  var rate = 13.26;
  if ( (w > max_w) ) {
    var time = w*rate;
    $("#alert-banner span").clone().appendTo("#alert-banner span");
    function scroll() {
      $("#alert-banner > span").animate( 
        {left:"-"+w+"px"}, time, 'linear', function() {
          $(this).css('left', '1em');
          scroll();
          });
    }
    scroll();
  } else {
    pad = max_w-w;
    var time = (pad+w)*rate;
    function bounce() {
      $("#alert-banner > span").animate( 
        {paddingLeft:pad+"px", paddingRight:pad+"0px"}, time, 'swing').animate({paddingRight:pad+"px", paddingLeft:"0px"}, time, 'swing', function() {
            bounce();
          });
    }
    bounce();
  }

// equalize columns.
  $.fn.v_justify = function() {
    var min_height = 100;
    $(this).find("div.column").each(function() {
      var element = $(this);
      if (element.height() > min_height) {
        min_height = element.height();
      }
    });
    $(this).find("div.column").css({height: min_height+"px"});
  };

  // input text from input titles ( used on search )
  function title_to_value() {
    input_field = $(this);
    if (input_field.attr("value") == input_field.attr("title")) {
      input_field.attr("value", '');
    }
  }
  function reset_to_value() {
    input_field = $(this);
    if (!input_field.attr("value")) {
      input_field.attr("value", input_field.attr("title"));
    }
  }
  $.fn.placeholder = function() {
    return this.each(function() {
      var input_field = $(this);

      // empty the field on click if it has default value
      input_field.bind("focus", title_to_value);

      // reset the field to default value on blur if it is empty
      input_field.bind("blur", reset_to_value);

      // empty the field if the same value as title before submitting
      $("form:has(input[name='"+input_field.attr("name")+"'])").bind('submit', title_to_value);

      // reset the field to the title
      $("form:has(input[name='"+input_field.attr("name")+"'])").bind('reset', function() {
        input_field.attr("value", input_field.attr("title"));
        return false;
      });

      input_field.attr("value", input_field.attr("title"));
    });
  };
  $(".js_placeholder").placeholder();



  /* Tabs by Chris */
  $('#related-tabs').tabs();

  /*$("div#subnav div.subnav_wrapper").prev().bind('mouseover', function(e) {
    var subnav_wrapper = $(this).next();
    subnav_wrapper.toggle(1000);
    e.preventDefault();
  });*/
  
  /* Datepicker by Chris */
  $('#dateArrive').datepicker({onSelect: function(){
    if($('#dateDepart').val() != ''){
      var numOfNights = dateDifference($('#dateDepart').val(),$('#dateArrive').val());
      $('#nights').val(numOfNights);
    }
  }});
  
  $('#dateDepart').datepicker({onSelect: function(){
    var numOfNights = dateDifference($('#dateDepart').val(),$('#dateArrive').val());
    if(!isNaN(numOfNights)){
      $('#nights').val(numOfNights);
    }
  }});
  
  function dateDifference(d1, d2){
    var date1 = new Date(d1);
    var date2 = new Date(d2);
    var diff = date1.getTime() - date2.getTime();
    
    if(diff <= 1){
      $('#dateDepart').val('');
      return;
    }
    var day = 1000*60*60*24; //milliseconds * seconds * minutes * hours
    var numberOfNights = Math.floor(diff/day);
    return numberOfNights;
  }
  
  $('#dateDepart').blur(function(){
    if($('#dateArrive').val() == '' && $('#dateDepart').val() != ''){
      $('#dateArrive').focus();
    }
  });
  
  $('#ui-datepicker-div').hide();
  // /++skin++pcmr.Summer/pcmr/@@/summer.cssjs/img/pcmr_summer_background_bottom.jpg
  // /@@/summer.cssjs/img/pcmr_summer_background_bottom.jpg
  $('body').css('background','#a2d2f8 url(/@@/summer.cssjs/img/pcmr_summer_background_bottom.jpg) repeat-x scroll left bottom');
  if($('#container').height() < $(window).height()) {
    $('#container').height($(window).height());
  }
  
  $(window).resize(function() {
    if($('#container').height() < $(window).height()) {
      $('#container').height($(window).height());
    }
  });
});


function shadowboxSetup() {
	Shadowbox.setup("a.mediagallery-link", {
		gallery: "Park City Mountain Resort Media Gallery",
		continuous: true,
		counterType: "skip"
	});
}

$(window).load(function(){
  //$("div#homepage_bottom-columns").v_justify();

});

function Go(sURL) {
  this.location.href = sURL;
}

function setGiveawayCookie() {
  if (document.cookie && document.cookie != "")
  {
    var old_cookie = document.cookie;  
    var exp = new Date();
    exp.setTime(exp.getTime() + 604800000);
    document.cookie = old_cookie + "giveawayPCMR=true; expires=" + exp.toUTCString();
  }
  else
  {
    var exp = new Date();
    exp.setTime(exp.getTime() + 604800000);
    document.cookie = "giveawayPCMR=true; expires=" + exp.toUTCString();
  }
}

/* 
 var exp = new Date();
 exp.setTime(exp.getTime() + 604800000);
 set_cookie('giveawayPCMR', 'true', exp.toUTCString());
*/
function set_cookie(name, value, expires, path, domain, secure) {
  var today = new Date();
  today.setTime(today.getTime());

  if (expires) {
    expires = expires * 100000 * 60 * 60 * 24 * 6;
  }
  var expires_date = new Date();
  expires_date.setTime(expires_date.getTime() + (expires));
  

  document.cookie = name + "=" +escape(value) +
    ((expires) ? ";expires=" + expires_date.toGMTString() : "") +
    ((path) ? ";path=" + path : "") +
    ((domain) ? ";domain=" + domain : "") +
    ((secure) ? ";secure" : "");
    
}

/* will return 'true' if you call get_cookie('giveawayPCMR') after setting it. */
function get_cookie(name) {
  var start = document.cookie.indexOf(name + "=");
  var len = start + name.length + 1;
  if ((!start) && (name != document.cookie.substring(0, name.length))) {
    return null;
  }
  if (start == -1) {
    return null;
  }
  var end = document.cookie.indexOf(";", len);
  if (end == -1) {
    end = document.cookie.length;
  }
  return unescape(document.cookie.substring(len, end));
}

function delete_cookie(name) {
    document.cookie = name + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
}
