// ~~~~~ FOLDERs ~~~~~
var folder = {
    IMAGES: '/images/',
    JAVASCRIPT: '/js/',
    FLASH: '/flash/',
    XML: '/xml'
};

// browser feature detection;
var isIE = ($.support.leadingWhitespace === false);
var isIE6 = ((window.XMLHttpRequest == undefined) && (ActiveXObject != undefined)) ? true : false;

(function($) {
    $.fn.clearInput = function() {
        this.focus(function() {
            if (this.value == this.defaultValue) this.value = "";
        }).blur(function() {
            if (this.value == "") this.value = this.defaultValue;
        });
    };

    $.fn.clearImage = function() {
        this.focus(function() {
            if (this.value == "") {
                $(this).removeClass("password");
                $(this).addClass("password-nobkgd");
            }
        }).blur(function() {
            if (this.value == "") {
                $(this).removeClass("password-nobkgd"); 
                $(this).addClass("password");
            }
        });
    };
	// ===== GLOBAL: Cached Version of $.getScript() =====
	$.getCachedScript = function(url, callback, cache){
		$.ajax({ type: "GET", url: url, success: callback, dataType: "script", cache: cache || true });
	}; 
    // ===== FIND AN OUTFITTER: Chained Select Filters =====
    $.fn.selectOutfitter = function(options) {
        // extend our default options with those provided
        var $options = $.extend({}, $.fn.selectOutfitter.defaults, options);

        return this.each(function() {
            var $this = $(this);
            $this.find('select:first').change(function() {
                if ($this.find('option:selected').val() != '') {
                    // enable disabled <select> list(s)
                    $this.find('select').not('#pros select').addClass('active').attr('disabled', '');
                } else {
                    var selects = $this.find('select').not(':first, #pros select');
                    selects.find('option:first').attr('selected', 'true');
                    selects.removeClass('active').attr('disabled', 'disabled');
                };
            });
            $('#category').bind((isIE) ? 'click' : 'change', function(e) {
                var nCat = $(this).find('option:selected').val();
                if (nCat != '') {
                    $('#species select').empty().html('<option value="">Select a Species</option>');
                    $('#location select').empty().html('<option value="">Select a Location</option>');
                    $('#price select').empty().html('<option value="">Select a Price</option>');
                    $.ajax({
                        url: '/ajax/GetCategoryLists.aspx?catId=' + nCat,
                        type: 'get',
                        dataType: 'xml',
                        success: function(xml) {
                            var options = [], i = 0, o = null;
                            var item = $(xml).find('specie');
                            for (x = 0, xl = item.length; x < xl; x++) {
                                // required to get around IE bug (http://support.microsoft.com/?scid=kb%3Ben-us%3B276228)
                                o = document.createElement("OPTION");
                                o.value = $(item[x]).attr('id');
                                o.text = $(item[x]).attr('name');
                                $('#species select').get(0).options[x + 1] = o;
                            };
                            $this.find('#species select').addClass('active').attr('disabled', '');

                            item = $(xml).find('location');
                            for (x = 0, xl = item.length; x < xl; x++) {
                                // required to get around IE bug (http://support.microsoft.com/?scid=kb%3Ben-us%3B276228)
                                o = document.createElement("OPTION");
                                o.value = $(item[x]).attr('id');
                                o.text = $(item[x]).attr('name');
                                $('#location select').get(0).options[x + 1] = o;
                            };
                            $this.find('#location select').addClass('active').attr('disabled', '');

                            if ($('#price select').get(0) != undefined) {
                                item = $(xml).find('price');
                                for (x = 0, xl = item.length; x < xl; x++) {
                                    // required to get around IE bug (http://support.microsoft.com/?scid=kb%3Ben-us%3B276228)
                                    o = document.createElement("OPTION");
                                    o.value = $(item[x]).attr('id');
                                    o.text = $(item[x]).attr('name');
                                    $('#price select').get(0).options[x + 1] = o;
                                };
                                $this.find('#price select').addClass('active').attr('disabled', '');
                            }

                            // hand control back to browser for a moment
                            setTimeout(function() {
                                $('#species select')
									.find('option:first')
									.attr('selected', 'selected')
									.trigger('change');
                            }, 0);
                        }
                    });
                };
            });
            $('#location').change(function() {
                if ($(this).find('option:selected').val() == '') {
                    $(this).find('option:first').attr('selected', 'true');
                };
            });

        });
    }
    // default option
    $.fn.selectOutfitter.defaults = {
    //
};

// ===== GLOBAL: Parse Querystring =====
$.param = function(name, href, defaultvalue) {
    var exp = new RegExp('[\\?&]' + name + '=([^&#]*)');
    var param = exp.exec((href) ? href : window.location.href);
    return (param) ? param[1] : (defaultvalue || null);
};

// ===== HUNTING: Must be logged in to view =====
$.fn.securedRedirect = function(options) {
    // extend our default options with those provided
    var $options = $.extend({}, $.fn.securedRedirect.defaults, options);

    var closeBtn = folder.IMAGES + 'closebox' + ((isIE6) ? '.gif' : '.png')
    var HTML;
    $.ajax({
        url: '/ajax/popuplogin.aspx',
        type: 'GET',
        data: "cb=" + closeBtn,
        dataType: 'html',
        success: function(xml) {
            HTML = xml;
        }
    });

    return this.each(function() {
        var $this = $(this);

        $this.click(function(e) {
            if ($('#sideColumn').find('div.welcome').length) return;
            e.preventDefault();

            // ~~~~~ reset ~~~~~
            if ($('#light').length) $('#light').remove();
            if ($('#fade').length) $('#fade').remove();

            // ~~~~~ Show Lightbox ~~~~~
            $('body').append('<div id="light" class="white_content"></div>').append('<div id="fade" class="black_overlay"></div>');
            $('#light').html(HTML);
            $('#fade').css({ 'display': 'block', 'opacity': 0.0, 'height': $('body').height() })
				.animate({ 'opacity': 0.8 }, 1000, function() {
				    $('#light').css({ 'display': 'block', 'opacity': 0.0 }).
					animate({ opacity: 1.0 }, 1000, function() {
					    if ($.browser.msie) $('#light').get(0).style.removeAttribute('filter');
					    if (isIE6) $('html, body').animate({ scrollTop: 0 }, 'fast');
					});
				});
            var login = $('#light').find('div.login');
            $(login).find('input.submit').bind('click', function(e) {
                e.preventDefault();
                var user = $(login).find('input[name="email"]').val(),
						pass = $(login).find('input[name="password"]').val();
                $.ajax({
                    url: '/ajax/loginProcessor.aspx',
                    type: 'POST',
                    data: "u=" + user + "&p=" + pass,
                    dataType: 'html',
                    success: function(xml) {
                        var sLogin = $.param('login', xml);
                        if (sLogin == 'success') {
                            window.location.href = ($this.attr('href')) ? $this.attr('href') : window.query;
                        } else if (sLogin == 'failure') {
                            $('#loginError').html(decodeURIComponent($.param('msg', xml).replace(/\+/g, " ")));
                            if (isIE) {
                                $('#light .signin').css('margin-top', 0);
                                $('#light .signin #loginError').css('margin-top', 0);
                            }
                        };
                    }
                });

            });
            $('#btnCloseLogin').click(function(e) {
                $('#light,#fade').css('display', 'none');
                //window.location.href = '/default.aspx';
                return false;
            });
        });
    });
};
// default option
$.fn.securedRedirect.defaults = {
//
};
})(jQuery);

// ===== Initial DOM Manipulation =====
jQuery(document).ready(function($) {
    // ~~~~~ GLOBAL: Toggle Input Default Values ~~~~~
    $('input:text').clearInput();
    $('.register input:password').clearImage();

    // ~~~~~ GLOBAL: Register / Sign-In ~~~~~
    // TABS:
    $('#btnJoin,#btnSignIn').click(function(e) {
        $('#sign-in,#join').toggleClass('hide');
        e.preventDefault();
    });

    // ~~~~~ TABS: Switch Content ~~~~~
    $('#tabs > div').hide();
    if ($('#tabs ul.tabs li').hasClass('selected')) {
        var $selected = $('#tabs ul.tabs');
        var index = $('li', $selected).index($('li.selected', $selected));
        $('#tabs > div').eq(index).show();
        $('#tabs ul.tabs li').eq(index).addClass('selected');
    } else {
        $('#tabs > div:first').show();
        $('#tabs ul.tabs li:first').addClass('selected');
    };
    $('#tabs ul.tabs li a').click(function(e) {
        $('#tabs ul.tabs li').removeClass('selected');
        $(this).parent().addClass('selected');
        var currentTab = $(this).attr('href');
        $("#tabs > div:visible").fadeOut("fast", function() {
            $(currentTab).fadeIn("fast");
        });
        return false;
    });

    // ~~~~~ VIDEO: Embed Player ~~~~~
    var videoPlayer = $('#videoPlayerIndex,#videoPlayerEmbed');
    if (videoPlayer.length) {
        if (!$('body.index')) {
            injectVideoPlayer();
        }
    };

    // ~~~~~ FILTER: Select Outfitter ~~~~~
    if ($('.filters').length) {
        $('.filters').selectOutfitter();
    };

    // ~~~~~ HUNTING: Must be logged in to view ~~~~~
    var huntingLinks = $('#content a[rel="secure"]');
    if (huntingLinks.length) {
        huntingLinks.securedRedirect();
    };
    // LEFT NAV:
    if ($('#navHUNT.selected').length && !$('#sideColumn .welcome').length) {
        $('#navHUNT.selected').find('input.find').securedRedirect();
    };

    $("#filterOutfitter").click(function(e) {
        var c = $("#category select").val();
        var s = $("#species select").val();
        var l = $("#location select").val();
        var p = $("#price select").val();
        var x = $("#pros select").val();
        var url = $("#filterUrl").val();
        var target = $("#filterTarget").val();

        var first = true;
        var qs = "";
        if (c != undefined && 0 != c.length) {
            if (false == first) qs = qs + "&";
            qs = qs + "c=" + c;
            first = false;
        }
        if (s != undefined && 0 != s.length) {
            if (false == first) qs = qs + "&";
            qs = qs + "s=" + s;
            first = false;
        }
        if (l != undefined && 0 != l.length) {
            if (false == first) qs = qs + "&";
            qs = qs + "l=" + l;
            first = false;
        }
        if (p != undefined && 0 != p.length) {
            if (false == first) qs = qs + "&";
            qs = qs + "p=" + p;
            first = false;
        }
        if (x != undefined && 0 != x.length) {
            if (false == first) qs = qs + "&";
            qs = qs + "x=" + x;
            first = false;
        }

        if (0 != qs.length) {
            url = url + "?" + qs;
        }

        window.query = url;
        if ($('#navHUNT.selected').length && !$('#sideColumn .welcome').length) {
            return false;
        } else {
            if (target != undefined && 0 != target.length) {
                window.open(url, target);
            } else {
                window.location.href = window.query;
            }
        };
        return false;
    });

    $("#search").keypress(function(e) {
        if (e.which == 13) {
            var searchTerm = $("#search").val();
            if (searchTerm != undefined && 0 != searchTerm.length) {
                location = "/search.aspx?term=" + escape(searchTerm);
                return false;
            }
        }
    });

    $("#search").click(function() {
        var searchTerm = $("#search").val();
        if (searchTerm != undefined && 0 != searchTerm.length && searchTerm != 'SEARCH') {
            location = "/search.aspx?term=" + escape(searchTerm);
            return false;
        }
    });

    // Homepage Password Press Enter Causes Login 
    $("#ctl00_Signin_login_password").keypress(function(e) {
        if (e.which == 13) {
            $("#ctl00_Signin_signInButton").click();
            return false;
        }
    });

    // Subpage Password Press Enter Causes Login
    $("#ctl00_ctl00_Signin_login_password").keypress(function(e) {
        if (e.which == 13) {
            $("#ctl00_ctl00_Signin_signInButton").click();
            return false;
        }
    });

    // ~~~~~ CAROUSEL ~~~~~
    var testimonials = $('#mainContent').find('.testimonials')
    if (testimonials.length) {
        testimonials.simpleCarousel({ 'showNextPrev': false, 'showPageNumbers': false, 'fade': 750 });
    };

    // ~~~~~ FAQ: Hide/Show Questions/Answers ~~~~~
    var FAQ = $('#AccordionList');
    FAQ.find('dd').hide();
    FAQ.find('dd.current').show();
    FAQ.find('dt').click(function() {
        $(this).addClass('active').siblings('dt').removeClass('active');
        $(this).next('dd:hidden').slideDown("fast", function() {
            if (jQuery.browser.msie) {
                $(this).css('height', $(this).height()); // kludge;
            };
        })
		.siblings('dd:visible').slideUp("slow", function() {
		    $(this).find('div').hide();
		}
		);
        return false;
    });

    // ~~~~~ GALLERY: Show Video Player || Show Full-Sized Images ~~~~~
    var videos = $('#tab-videos-inline a,#AccordionList a.btn');
    var gallery = $('#tab-photos a[rel=photo]');
    if (videos.length || gallery.length) {
        $('head').append('<link type="text/css" rel="stylesheet" media="screen" href="/css/jquery.fancybox.css" />');
        $.getScript('/js/jquery.fancybox-1.2.1.pack.js', function() {
            // ~~~~~ video player ~~~~~
            if (videos.length) {
                $('body').append('<div id="inlineVideo" style="display:none;"><div><span id="videoIDList" style="display:none;"></span><div id="pdkHolder"><div class="commmanager"><div id="commmanagerDiv"></div></div><div class="player"><div id="playerDiv"></div></div></div>');
                videos.fancybox({
                    frameWidth: 547,
                    frameHeight: 363,
                    overlayOpacity: 0.7,
                    hideOnContentClick: false,
                    callbackOnShow: function() {
                        var sVideoList = $('#inlineVideo').attr('rel');
                        var pid = sVideoList.split('=')[1];
                        $.getScript('/js/platform/util.js', function() {
                            $.getScript('/js/jquery.videoplayer.js', function() {
                                var thisAdService = "";
                                var thisAdZone = "";
                                var thisAdKW = "";
                                var thisAdPos = "";
                                var thisAdTile = "";
                                var thisAdURL = "";
                                var thisRandomFirst = false;
                                var thisReloadClick = true;

                                $('#videoIDList').append(pid);
                                $('#inlineVideo').videoPlayerThePlatform({ 'PID': pid, 'AdService': thisAdService, 'AdZone': thisAdZone, 'AdKW': thisAdKW, 'AdPos': thisAdPos, 'AdTile': thisAdTile, 'AdURL': thisAdURL, 'RandomFirst': thisRandomFirst, 'ReloadClick': thisReloadClick });
                            });
                        });
                    },
                    callbackOnClose: function() {
                        $("#fancy_content object").remove();
                    }
                }).click(function(e) {
                    $('#inlineVideo').attr('rel', $(this).attr('rel'));
                    e.preventDefault();
                });
            };
            // ~~~~~ photo gallery ~~~~~
            if (gallery.length) {
                gallery.fancybox({ 'overlayOpacity': 0.7 });
            };
        })
    };

});

// ===== WEATHER MODULE: Display weather based on location =========================
var WeatherSideModule = function() {
    var config = {};

    function init() {
        if ($('div.weather').length) {
            $.getCachedScript(folder.JAVASCRIPT + 'jquery.weather.js', function() {
                var savedLocation = ($('body.index').length) ? $.cookie('weatherSearchedLocation') : null;
                events(savedLocation);
            });

        };
    };

    function events(localeFromSearch) {
        var module = $('div.weather')
        var locale = localeFromSearch || module.attr('class').replace(/weather \{(.*)}/ig, '$1');
        var fromCookie = (localeFromSearch != null) ? true : false;
        module.showForecast({
            nDaysInForecast: 3,
            sLocale: locale,
            bFromCookie: fromCookie
        });
    };

    function update(fromSearch) {
        events(fromSearch);
    };

    return { config: config, init: init, update: update }
} ();

function injectVideoPlayer() {
    if ($('#videoPlayerPlaceholder').length) {
        $('#videoPlayerPlaceholder').addClass('hide');
    }

    if ($('#videoPlayerContainer').length) {
        if ($('#videoPlayerContainer').hasClass('hide')) {
            $('#videoPlayerContainer').removeClass('hide');
        }

        $.getScript('/js/platform/util.js', function() {
            $.getScript('/js/jquery.videoplayer.js', function() {
                InjectPlayer();
            });
        });
    }
};

function reloadPage() {
    window.location = window.location;
};

// ===== Non-Essential DOM Events =====
var $jq = jQuery;
$jq(window).load(function() {
    // ~~~~~ 
    if ($jq('#videoIntroduction').length) {
        var file = $jq.trim($jq('#videoIntroduction span.video').text());
        var image = $jq.trim($jq('#videoIntroduction span.image').text());

        // load the video player
        if (swfobject.hasFlashPlayerVersion("9.0.0")) {
            var att = { data: folder.FLASH + 'videoHost.swf', width: 462, height: 260, menu: 'false', id: 'oeVideoHost', name: "oeVideoHost" };
            var par = { wmode: 'transparent', swliveconnect: 'true', allowfullscreen: 'true', allowscriptaccess: 'always', flashvars: '&video=../' + file + '&index=' + (($('body').hasClass('index')) ? 'true' : 'false') + '&image=' + image };
            var id = "videoHostPlayer";
            var so = swfobject.createSWF(att, par, id);
            if ($('body.index').length) {
                if ($('#videoPlayerContainer').length) {
                    $('#videoPlayerContainer').parent().append('<div id="videoPlayerPlaceholder" style="margin: 15px -2px 0 0"><img src="' + folder.IMAGES + '/video_index_placeholder.jpg" width="920" height="515" alt="" /></div>');
                    $('#videoPlayerContainer').addClass('hide');
                }
            }
        } else {
            $jq('#videoHostPlayer').set('html', '<h2>Please <a href="http://www.adobe.com/products/flashplayer/" target="blank">upgrade your Flash Player</a><br /> to experience this site to its fullest.</h2>');
        };
    } else {
        injectVideoPlayer();
    };

    // ~~~~~ WEATHER ~~~~~
    WeatherSideModule.init();
});