//cookie management http://www.quirksmode.org/js/cookies.html
function setCookie(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 getCookie(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 deleteCookie(name) {
    setCookie(name, "", -1);
}

//TODO: wrap functs in general behavior object, factor out constants
(function ($) {

    function PageBehavior() {
        this.configVars = {
            PvInitDelay: 1500,
            SearchPageUrl: 'http://www.sunvalley.com/search/#/'
        };
    }

    //dropdown menus
    PageBehavior.prototype.initDropMenu = function() {
        $("#nav > li:has(div)").hover(function () {
            $(">div", this).show();
        }, function () {
            $(">div", this).hide();
        });

        $("#nav li li").hover(function(){
		    $(this).addClass("over")
	    },function(){
		    $(this).removeClass("over")
	    });
    };

    //search string encoding
    PageBehavior.prototype.encodeForSearchPage = function(searchString) {
        var searchData = searchString.split(' ');
        var normalized = "";
        for (var i = 0; i < searchData.length; i++) {
            normalized += searchData[i];
            if (i < searchData.length - 1) normalized += '+';
        }
        return this.configVars.SearchPageUrl + normalized;
    };

    //image stack rotation
    PageBehavior.prototype.swapElement = function(elementWrapper, index, prevIndex, fadeDuration) {
        elementWrapper.eq(index).fadeIn(fadeDuration, function () {
            elementWrapper.eq(prevIndex).hide();
        });
    }

    //combo snow/weather/cams widget
    function ComboWidget() {
		//SET COMBO WIDGET PREFS
		var cwPrefs = getCookie('comboWidgetPrefs');
		if (cwPrefs != null) {
			if (cwPrefs == '0') {
				this.cwCollapsed = true;
			}
			else {
				this.cwCollapsed = false;
			}
		}
    }
	
	ComboWidget.prototype.isCollapsed = function() {
		return this.cwCollapsed;
	}
	
	ComboWidget.prototype.expand = function(animate) {
		var cbWidgetGroup = $('#comboWidgetGroup');
		
		if (animate) {
			cbWidgetGroup.animate({left: 0},
			function() {
				$('#comboWidgetGroup').removeClass('closed');
				$('#comboWidgetToggleBox').removeClass('closed');
				$('#comboWidgetGroup').attr('style', '');
			});
		}
		else {
			$('#comboWidgetGroup').removeClass('closed');
			$('#comboWidgetToggleBox').removeClass('closed');
		}
		
		setCookie('comboWidgetPrefs', '1', 365);
	};
	
	ComboWidget.prototype.collapse = function(animate) {
		var cbWidgetGroup = $('#comboWidgetGroup');
		
		if (animate) {
			cbWidgetGroup.animate({left: cbWidgetGroup.parent().outerWidth() - 25},
			function() {
				$('#comboWidgetGroup').addClass('closed');
				$('#comboWidgetToggleBox').addClass('closed');
				$('#comboWidgetGroup').attr('style', '');
			});
		}
		else {
			$('#comboWidgetGroup').addClass('closed');
			$('#comboWidgetToggleBox').addClass('closed');
		}
		
		setCookie('comboWidgetPrefs', '0', 365);
	};
	
	ComboWidget.prototype.toggle = function() {
		var cbWidgetGroup = $('#comboWidgetGroup');
		if (cbWidgetGroup.hasClass('closed')) {
			this.expand(true);
		}
		else {
			this.collapse(true);
		}
	};

    function BookingWidget() {
		this.rangeOpen = true;
		this.arrDate = new Date();
		this.arrDate.setDate(this.arrDate.getDate() + 1);
		this.depDate = new Date();
		this.depDate.setDate(this.arrDate.getDate() + 1);
	};
	BookingWidget.prototype.updateDateFields = function(selectedDate) {
		if (this.rangeOpen) {
			this.arrDate = selectedDate;
			this.depDate = new Date(this.arrDate); //pass by val and set to same day then increment 1 day
			this.depDate.setDate(this.arrDate.getDate() + 1);
			this.rangeOpen = false;
		}
		else {
			if (selectedDate < this.arrDate) {
				this.depDate = this.arrDate;
				this.arrDate = selectedDate;
			}
			else if (selectedDate > this.arrDate) {
				//do nothing if ==
				this.depDate = selectedDate;
			}
			this.rangeOpen = true;
		}
		this.fillDateFields();
	};
	BookingWidget.prototype.fillDateFields = function() {
		$("input#arrival_date").val(this.formatMonth(this.arrDate.getMonth()) + '/' + this.arrDate.getDate() + '/' + this.arrDate.getFullYear());
		$("input#departure_date").val(this.formatMonth(this.depDate.getMonth()) + '/' + this.depDate.getDate() + '/' + this.depDate.getFullYear());
	};
	BookingWidget.prototype.hilightRange = function(date) {
		if ((date >= this.arrDate) && (date <= this.depDate)) {
			return [true, 'ui-datepicker-range'];
		}
		else return [true, ''];
	};
	BookingWidget.prototype.formatMonth = function(mIndex) {
		return mIndex + 1;
	};
	BookingWidget.prototype.getUrl = function(baseUrl) {
		var arrDate = new Date(Date.parse($("input#arrival_date").val()));
		var depDate = new Date(Date.parse($("input#departure_date").val()));
		var ad = $('#ad option:selected').val();
		var ch = $('#ch option:selected').val();

		var y = arrDate.getFullYear();
		var m = this.formatMonth(arrDate.getMonth());
		var d = arrDate.getDate();
		var one_day = 86400000;
		var timeDiff = depDate.getTime() - arrDate.getTime();
		var days = Math.ceil(timeDiff / one_day);

		return baseUrl + '#/sun-valley-lodge/' + y + "/" + m + "/" + d + "/" + days + "/" + ad + "/" + ch;
	};

    //new instances of objects
    window.pageBehavior = new PageBehavior();
    window.comboWidget = new ComboWidget();
    window.bookingWidget = new BookingWidget();

    // Return a new application instance.
    //return (window.pageBehavior);
})(jQuery);

//news ticker plugin
(function ($) {
    var methods = {
        init : function(options) {
            var settings = {
                'index': 0,
                'max': this.children().length - 1
            };
            var context = this;

            return this.each(function() {
                //merge passed in options with defaults
                if (options) {
                    $.extend(settings, options);
                }

                //run meat of it
                context.everyTime(8000, function() {
                    var index = settings['index'];
		            var prevIndex = index;
		            if (index == settings['max']) index = 0;
		            else index++;
                    settings['index'] = index;

                    var prev = context.children().eq(prevIndex);
                    var cur = context.children().eq(index);
                    prev.animate({top: -15}, 500,
			            function() {
				            prev.attr('class', 'inactive');
				            prev.attr('style', '');
			            });
                    cur.animate({top: 0}, 500,
			            function() {
				            cur.attr('class', 'current');
				            cur.attr('style', '');
			            });

	            }, 0);
            });
        },
        destroy : function() {
            //
        }
    };


    $.fn.NewsTicker = function(method) {
        if ( methods[method] ) {
            return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.NewsTicker' );
        }   
    };
})(jQuery);

//plasma client plugin
(function ($) {
    var methods = {
        init: function (options) {
            var settings = {
                'index': 0,
                'max': this.children().length - 1
            };
            var context = this;

            return this.each(function () {
                //merge passed in options with defaults
                if (options) {
                    $.extend(settings, options);
                }

                //run meat of it
                context.everyTime(7000, function () {
                    var index = settings['index'];
                    var prevIndex = index;
                    if (index == settings['max']) index = 0;
                    else index++;
                    settings['index'] = index;

                    pageBehavior.swapElement(context.children(), index, prevIndex, 600);

                }, 0);
            });
        },
        destroy: function () {
            //
        }
    };


    $.fn.PlasmaClient = function (method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.PlasmaClient');
        }
    };
})(jQuery);

//tab bar plugin
(function ($) {
    var methods = {
        init : function(options) {
//            var settings = {
//                'index': 0,
//                'max': this.children().length - 1
//            };
            var context = this;
            var addressPlugin = false;
            if (jQuery().address) {
                addressPlugin = true;
            }

            return this.each(function() {
                //merge passed in options with defaults
                if (options) {
                    $.extend(settings, options);
                }

                //plugin logic
                if (context.is('.fulldoc')) {
                    $('li a', context).each(function (i, o) {
                        $(o).attr("href", "javascript:void(null)");
                    });

                    $('li a.tab', context).click(function () {
                        $('#tabs_container .tabs > li.active').removeClass('active');
                        $('#tabs_container .tabIsolatedRight.active').removeClass('active');
                        //alert($(this).closest('.tabLeft').html());
                        $(this).closest('.tabLeft').addClass('active');
                        $(this).closest('.tabIsolatedRight').addClass('active');
                        $('#tabs_container > .tabbed_content > div.active').removeClass('active');
                        $(this.rel).addClass('active');

                        if (addressPlugin) {
                            var curTab = helpers.getTabUrlFragment($.address.path()),
			                    curFragment = $.address.value(); //might be something other than a tab
                            if ((curFragment.length > 0) && (curTab.length > 0)) {
                                $.address.value($.address.value().replace(curTab, this.rel.substring(1)));
                            }
                            else if (curFragment.length > 0) {
                                $.address.value(this.rel.substring(1) + curFragment);
                            }
                            else {
                                $.address.value(this.rel.substring(1));
                            }
                        }
                    });

                    if (addressPlugin) {
                        $.address.externalChange(function () {
                            var _address = $.address.path();
                            if (_address != '/') {
                                var _rel = '#' + _address.substring(1),
                                    _tracker = _address.substring(1),
				                    _tS = _rel.indexOf('/', 0); //look for fragment variables below l3 and ignore them
                                if (_tS > -1) {
                                    _rel = _rel.substring(0, _tS);
                                    _tracker = _tracker.substring(0, _tS);
                                }
                                $('#tabs_container .tabs > li.active').removeClass('active');
                                $('#tabs_container .tabIsolatedRight.active').removeClass('active');
                                $('a[rel=' + _rel + ']', context).closest('.tabLeft').addClass('active');
                                $('a[rel=' + _rel + ']', context).closest('.tabIsolatedRight').addClass('active');
                                $('#tabs_container > .tabbed_content > div.active').removeClass('active');
                                $(_rel).addClass('active');

                                helpers.trackFragmentNav(_tracker);
                            }
                            else {
                                //go to first tab with / on back button, etc
                                $('#tabs_container .tabs > li.active').removeClass('active');
                                $('.tabLeft', context).filter(':first').addClass('active');
                                $('#tabs_container > .tabbed_content > div.active').removeClass('active');
                                var _rel = $('a', context).filter(':first').attr('rel');
                                $(_rel).addClass('active');
                            }
                        });

                        $.address.internalChange(function () {
                            var _address = $.address.path();

                            if (_address != '/') {
                                var _rel = _address.substring(1),
                                _tS = _rel.indexOf('/', 0); //look for fragment variables below l3 and ignore them
                                if (_tS > -1) {
                                    _rel = _rel.substring(0, _tS);
                                }

                                helpers.trackFragmentNav(_rel);
                            }
                        });
                    }
                }
                else {
                    //look for fragment markup and reassign hrefs to go to top level js powered nav
                    //var tabsFragment = $('fragment', context);
                    if (context.length > 0) {
                        $('li a', context).each(function (i, o) {
                            var tabUrl = $(o).attr("href"),
                                idx = tabUrl.lastIndexOf('/'),
                                slug = tabUrl.substring(idx),
                                baseUrl = tabUrl.substring(0, idx);
                            $(o).attr("href", baseUrl + "#" + slug);
                        });
                    }
                }
            });
        },
        destroy : function() {
            //
        }
    };

    var helpers = {
        getTabUrlFragment : function(path) {
            var tabNames = [],
		        fragment = path.substring(1), //assume initial '/'
		        _tS = fragment.indexOf('/', 0); //look for fragment variables below l3 and strip them off

            $('ul.tabs > li a').each(function (i, o) {
                tabNames.push($(o).attr('rel').substring(1));
            });

            if (_tS > -1) fragment = fragment.substring(0, _tS);
            if ($.inArray(fragment, tabNames) > -1) {
                return fragment;
            }
            else {
                return "";
            }
        },
        trackFragmentNav : function(fragmentID) {
        if (window.hasTrackFragments) {
            $.each(window.ebTrackFragments, function (i, trackTuple) {
                if (trackTuple.fragment == fragmentID) {
                    var conversionID = trackTuple.tag;
                    var trackingUrl = "http://bs.serving-sys.com/BurstingPipe/ActivityServer.bs?cn=as&ActivityID=" + conversionID + "&rnd=" + (Math.round(Math.random() * 1000000));
                    $.getScript(trackingUrl);
                    return false;
                }
            });
        }
    }
    };

    $.fn.TabNav = function(method) {
        if ( methods[method] ) {
            return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.TabNav' );
        }   
    };
})(jQuery);

//vertical tab plugin
(function ($) {
    var methods = {
        init : function(options) {
            var settings = {
                'index': 0,
                'max': this.children().length - 1
            };
            var context = this;

            return this.each(function() {
                //merge passed in options with defaults
                if (options) {
                    $.extend(settings, options);
                }

                //run meat of it
                $(context).each(function (i, o) {
					$('.v-tabs a.v-tab', o).click(function () {
						$('.v-tabs > li.active', o).removeClass('active');
						$(this).parent().addClass('active');
						$('div.active', o).removeClass('active');
						$(this.rel).addClass('active');
					});
				});
			
				$('.v-tabs a.v-tab', context).each(function (i, o) {
					$(o).attr("href", "javascript:void(null)");
				});
				$('div.content', context).each(function (i, o) {
				});
            });
        },
        destroy : function() {
            //
        }
    };


    $.fn.VerticalTabNav = function(method) {
        if ( methods[method] ) {
            return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.VerticalTabNav' );
        }   
    };
})(jQuery);

//collapsible widget plugin
(function ($) {
    var methods = {
        init : function(options) {
            var settings = {
                'index': 0,
                'max': this.children().length - 1
            };
            var context = this;

            return this.each(function() {
                //merge passed in options with defaults
                if (options) {
                    $.extend(settings, options);
                }

                //run meat of it (inner 'this')
                $('.header > a', this).click(function () {
					var header = $(this).parent();
					if (header.hasClass('expanded')) {
						header.removeClass('expanded');
						header.siblings('.content-collapsible').removeClass('expanded');
						header.siblings('.closeBottom').addClass('collapsed');
					}
					else {
						header.addClass('expanded');
						header.siblings('.content-collapsible').addClass('expanded');
			
						if (header.siblings('.closeBottom').length < 1) {
							header.parent().append('<a href="javascript:void(null)" class="closeBottom">[close]</a>');
							//must define .closeBottom click handler inline here b/c such doesn't exist at time of $(document).ready
							header.siblings('.collapsible .closeBottom').click(function () {
								if ($(this).siblings('.content-collapsible').hasClass('expanded')) {
									$(this).siblings('.content-collapsible').removeClass('expanded');
									$(this).siblings('.header').removeClass('expanded');
									$(this).addClass('collapsed');
								}
							});
						}
						else {
							header.siblings('.closeBottom').removeClass('collapsed');
						}
					}
				});
            });
        },
        destroy : function() {
            //
        }
    };


    $.fn.CollapsibleWidget = function(method) {
        if ( methods[method] ) {
            return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.CollapsibleWidget' );
        }   
    };
})(jQuery);

$(document).ready(function () {

    $('.slide-show').XW_slider({ buttonPosition: 'leftBottom', buttonOffsetX: 15, buttonOffsetY: 8, pn: true });

    pageBehavior.initDropMenu();

    $('#comboWidgetToggleBox').click(function () {
        comboWidget.toggle();
    });

    //set combo widget prefs
    if (comboWidget.isCollapsed()) {
        comboWidget.collapse(false);
    }
    else {
        comboWidget.expand(false);
    }

    $('#comboWidgetBody .tab').click(function () {
        $('#comboWidgetBody > .header > .headerContent > a.active').removeClass('active');
        $(this).addClass('active');
        $('#comboWidgetBody > .content').removeClass('active');
        $(this.rel).addClass('active');
    });

    var camWrapper = $('#pnl3 .cams > .webcams > .cam');
    var cMaxIndex = camWrapper.length - 1;
    var camIndex = 0;
    // only show the first image, hide the rest
    camWrapper.hide().filter(':first').show();

    $('#pnl3 a.navLeft').click(function () {
        var prevIndex = camIndex;
        if (camIndex == 0) camIndex = cMaxIndex;
        else camIndex--;
        pageBehavior.swapElement(camWrapper, camIndex, prevIndex, 500);
    });

    $('#pnl3 a.navRight').click(function () {
        var prevIndex = camIndex;
        if (camIndex == cMaxIndex) camIndex = 0;
        else camIndex++;
        pageBehavior.swapElement(camWrapper, camIndex, prevIndex, 500);
    });

    //init plasma client
    if ($('#plasmaClient ul').length > 0) {
        $('#plasmaClient ul').PlasmaClient();
    }

    //init news ticker
    if ($('#tickerRight').length > 0) {
        $('#tickerRight').NewsTicker();
    }

    //init client side blog sidebar
    if ($('.blog-list').length > 0) {
        var blogList = $('.blog-list ul');
        $.ajax({
            url: '/BlogWidgetJson.pxml',
            success: function (data) {
                blogList.empty();
                $.each(data.blogEntries.blogEntry, function (i, entry) {
                    var li = $('<li><a target="_blank"></a><p></p></li>');
                    $('a', li).text(entry.headline).attr('href', entry.permaLink);
                    $('p', li).html(entry.summary);
                    blogList.append(li);
                });
            }
        });
    }

    //init tab navigation
    if ($('#tabs_container ul.tabs').length > 0) {
        $('#tabs_container ul.tabs').TabNav();
    }

    $('.v-tab-container').VerticalTabNav();
    $('.collapsible').CollapsibleWidget();

    //begin booking widget
    $("#datepicker").datepicker({
        onSelect: function (dateText, inst) {
            var selectedDate = new Date(Date.parse(dateText));
            bookingWidget.updateDateFields(selectedDate);
        },
        beforeShowDay: hilightRangeLocal
    });

    bookingWidget.fillDateFields();

    function hilightRangeLocal(date) {
        return bookingWidget.hilightRange(date);
    }

    $("#arrival_date").datepicker({
        onSelect: function (dateText, inst) {
            arrDate = new Date(Date.parse(dateText));
            depDate = new Date(arrDate); //pass by val and set to same day then increment 1 day
            depDate.setDate(arrDate.getDate() + 1);
            bookingWidget.arrDate = arrDate;
            bookingWidget.depDate = depDate;
            bookingWidget.fillDateFields();
            $("#datepicker").datepicker("setDate", depDate)
        },
        showOn: "button",
        buttonImage: "/images/btn_calendar.png",
        buttonImageOnly: true
    });
    $("#departure_date").datepicker({
        onSelect: function (dateText, inst) {
            depDate = new Date(Date.parse(dateText));
            bookingWidget.depDate = depDate;
            bookingWidget.fillDateFields();
            $("#datepicker").datepicker("setDate", depDate)
        },
        showOn: "button",
        buttonImage: "/images/btn_calendar.png",
        buttonImageOnly: true
    });

    $('#roomSearch').click(function () {
        window.location.href = bookingWidget.getUrl("/trip-planner/lodging/");
    });

    //searchbox events
    $('#search button').click(function () {
        var searchString = $("#search input").val();
        window.location.href = pageBehavior.encodeForSearchPage(searchString);
    });
    $("#search").live("keypress", function (e) {
        if (e.keyCode == 13) {
            var searchString = $("#search input").val();
            window.location.href = pageBehavior.encodeForSearchPage(searchString);
        }
    });

});
