function initHeaderSlide() {
    $("#popup-link").click(function() {
        $("#slide").slideToggle(500);
        return false;
    });
};

function initWidget() {
    showMap("tab", 0);
    $("#tabset a").click(function() {
        $("#tabset a").removeClass("active");
        $(this).addClass("active");
        showMap("tab", $("#tabset a").index(this));
        //return false;
    });
};

function showMap(cssClass, idx) {
    $("div." + cssClass).hide();
    $("div."+ cssClass +":eq(" + idx + ")").show();
};

function initMap() {
    if ($("#map-main").length) {
        
        var startingTabIndex = 1;
        if (window.location.hash && window.location.hash.length == 10) {
            startingTabIndex = parseInt(window.location.hash.substring(9));
        };

        showMap("tab-main", startingTabIndex - 1);
        $("#tabset-main li a:eq(" + (startingTabIndex - 1) + ")").addClass("active");
        
        $("#tabset-main a").click(function() {
            $("#tabset-main a").removeClass("active");
            $(this).addClass("active");
            showMap("tab-main", $("#tabset-main a").index(this));            
        });
    };
};

function initWinResize() {
	var _width = 0;
	var _sblock = $('#header .head-box').eq(0);

	$(window).resize(function(){
		if (window.innerWidth) _width = window.innerWidth;
		else _width = document.documentElement.clientWidth;

		if(_width < 1200) {
			if(_width >= 1000)
				_sblock.css({marginRight:(1200-_width)/2});
		} else {
			_sblock.css({marginRight:0});
		}
	});
	$(window).resize();
};

function topHover() {
    $("#explore-links a:not(.current)")
        .mouseover(function() {
            var img = $(this).find("img");
            $(img).attr("src", $(img).attr("src").replace(".gif", "_d.gif"));
        })
        .mouseout(function() {
            var img = $(this).find("img");
            $(img).attr("src", $(img).attr("src").replace("_d.gif", ".gif"));
        });
};

function initBannerNav() {

    var $bannerNav = $("#main-image-nav");
    if ($bannerNav.length) {
        $bannerNav.show(); // show all dots
        var numBanners = $("img", $bannerNav).length;
        var curBanner = $("img", $bannerNav).index($("img.active", $bannerNav)) + 1;
        var curBannerCount = 1;

        // preload all banners except the current
        var $preloaderDiv = $("#preloaders");
        $bannerNav.find("a").each(function() {
            if (! $(this).children().hasClass("active") ) {
                $preloaderDiv.append("<img src='" + $(this).attr("rel") + "' />");
            };            
        });
        
        // load banners in order, once
        var bannerTimerId = setInterval(function() {
            if (curBannerCount < numBanners) {            
                curBannerCount++;
                curBanner++;
                if (curBanner > numBanners) { curBanner = 1; }; 
                loadRandomBanner($bannerNav, $("img:eq(" + (curBanner - 1) + ")", $bannerNav));
            };
        }, 5000);
        
        // handle dot click
        $("img", $bannerNav)
           .click(function() {
               loadRandomBanner($bannerNav, $(this));
               clearInterval(bannerTimerId); // stop rotation
               return false;
           })
           .mouseover(function() {
               $(this).attr("src", "/images/main-image-nav-hover.png").bind("mouseout", mouseoutBannerNav);
           });
                  
    };

    // don't follow an empty url
    $("#banner-cont a").click(function() {
        if ($(this).attr("href") == '') { $(this).attr("href", $(".main-image-link").attr("href")) };
    });

};

function mouseoutBannerNav() {
    if (!$(this).hasClass("active")) {
        $(this).attr("src", "/images/main-image-nav.png");
    };
};

function loadRandomBanner($bannerNav, $imgDot) {

    if (!$imgDot.hasClass("active")) {
        $("#banner").animate({ opacity: 0.0 }, 700, function() {
            var $cont = $("#banner-cont");
            var $imgHref = $imgDot.parent();
            // set banner
            $("img", $cont).attr({ src: $imgHref.attr("rel"), title: $imgDot.attr("title"), alt: $imgDot.attr("alt") }).animate({ opacity: 1.0 }, 700);
            // set url
            $("a", $cont).attr("href", $imgHref.attr("href"));
            // set dots
            $("img", $bannerNav).removeClass("active").attr("src", "/images/main-image-nav.png");
            $imgDot.addClass("active").attr("src", "/images/main-image-nav-hover.png").unbind("mouseout");
        });
    };

};

function initOperatorSearch() {

    if ($("#search-form").length) {

        // init tabs
        var $tabs = $("#operator-tabs");
        if ($tabs.length) {
            setOperatorSelects($("li.selected", $tabs))
            $tabs.addClass("styledtabs");
        };

        // hide communities on load, show or hide communities on region change
        var $regionsSelect = $("#operator-regions");
        toggleCommunitiesSelect($("option:selected", $regionsSelect).val());
        $regionsSelect.change(function() {
            toggleCommunitiesSelect($(this).val());
        });

        // community selection
        $("#frm-community-search select").change(function() {
            window.location.href = 'index.aspx?l=' + $(this).val();
        });

        // tabs label click
        $("label", $tabs).click(function() {
            $("li", $tabs).removeClass("selected");
            $(this).parent().addClass("selected");
            $("#filterhd").val($(this).attr("class")); // set filtered value
            setOperatorSelects($(this).parent())

        });

        // reset paging count on change
        $("#search-form select").change(function() {
            $("#current-page").val("1");
        });

        // search or look for hash, but not if we're on the google map
        if (! $("#operators-map").length) {

            // check for hash and do search if found
            if (location.hash.length > 0 && location.hash.substring(0,7) == '#filter') {
                operatorSearch(location.hash.substring(1));
            };
            
            // handle search
            $("#bt-operator-search").click(function() {
                var operatorSearchParams = $("#frm-operator-search").serialize();
                location.hash = '#' + operatorSearchParams;
                operatorSearch(operatorSearchParams);
                return false;
            });
        };

        // search results delegation: click outside of a
        $("#operator-search-results").click(function(e) {
            if ($(e.target).is("a") && $(e.target).parent().is("div.paging-links")) {
                $("#current-page").val($(e.target).attr("title")); // set currentpage to the title of the paging link
                $("#bt-operator-search").trigger("click");
                return false;
            };
        });

    };

};

function operatorSearch(params) {

    $.ajax({
        type: "GET",
        cache: false,
        url: "/" + $("#lang-name").val() + "/controls/operator_search.aspx",
        data: params,
        success: function(html) {
            $("#operator-search-results").html(html);
        }
    });

};

function toggleCommunitiesSelect(regionId) {
    
    var $communitiesSelect = $("#operator-communities"); // communities select box
    var $communitiesSelectStyled = $(".selectOptions:eq(4)"); // styled communities select box
    // reset - show all communities
    $("li", $communitiesSelectStyled).show();
    // hide all non-matching communities
    if (regionId) {
        $("option[class!=p" + regionId + "]", $communitiesSelect).each(function() {
            $("ul li:eq(" + $("option", $communitiesSelect).index(this) + ")", $communitiesSelectStyled).hide();
        });
    };

};

// hides all non-regional operator select boxes, shows the box that corresponds with the selected tab index
function setOperatorSelects($li) {
    $("#search-form .selectArea:lt(3)").hide();
    var idx = $("#operator-tabs li").index($li);
    $("#search-form .selectArea:eq(" + idx + ")").show();
};

// listens to operator search results / events row clicks
function searchResultsRowListener() {
    $(".operator-row").click(function() {
        window.location.href = $(this).find("a").attr("href");
        return false;
    });
};

function clearDefault() {
    if ($(this).val() == $(this).attr("title")) $(this).val("");
};

// striping
function memberDocs() {
    var table = $("#members-docs");
    if ($(table).length) {
        $("tr:even td", $(table)).addClass("dark");
    };
};

// jquery main
$(document).ready(function() {
    initHeaderSlide();
    initWinResize();
    initWidget();
    initMap();
    topHover();
    initBannerNav();
    $("#frm-operator-search select, #frm-community-search select").customSelect();
    initOperatorSearch();
    $("input.login-input").focus(clearDefault);
    memberDocs();
    searchResultsRowListener();

});

/*--- custom select function ---*/
jQuery.fn.customSelect = function(_options) {
    var _options = jQuery.extend({
        selectStructure: '<div class="selectArea"><div class="left"></div><div class="center"></div><a href="#" class="selectButton">&nbsp;</a><div class="disabled"></div></div>',
        selectText: '.center',
        selectBtn: '.selectButton',
        selectDisabled: '.disabled',
        optStructure: '<div class="selectOptions"><ul></ul></div>',
        optList: 'ul'
    }, _options);
    return this.each(function() {
        var select = jQuery(this);
        if (!select.hasClass('outtaHere')) {
            if (select.is(':visible')) {
                var replaced = jQuery(_options.selectStructure);
                var selectText = replaced.find(_options.selectText);
                var selectBtn = replaced.find(_options.selectBtn);
                var selectDisabled = replaced.find(_options.selectDisabled).hide();
                var optHolder = jQuery(_options.optStructure);
                var optList = optHolder.find(_options.optList);
                if (select.attr('disabled')) selectDisabled.show();
                select.find('option').each(function() {
                    var selOpt = $(this);
                    var _opt = jQuery('<li><a href="#">' + selOpt.html() + '</a></li>');
                    if (selOpt.attr('selected')) {
                        selectText.html(selOpt.html());
                        _opt.addClass('selected');
                    }
                    _opt.children('a').click(function() {
                        optList.find('li').removeClass('selected');
                        select.find('option').removeAttr('selected');
                        $(this).parent().addClass('selected');
                        selOpt.attr('selected', 'selected');
                        selectText.html(selOpt.html());
                        select.change();
                        optHolder.hide();
                        return false;
                    });
                    optList.append(_opt);
                });
                replaced.width(select.outerWidth());
                replaced.insertBefore(select);
                optHolder.css({
                    width: select.outerWidth(),
                    display: 'none',
                    position: 'absolute'
                });
                jQuery(document.body).append(optHolder);

                var optTimer;
                replaced.hover(function() {
                    if (optTimer) clearTimeout(optTimer);
                }, function() {
                    optTimer = setTimeout(function() {
                        optHolder.hide();
                    }, 200);
                });
                optHolder.hover(function() {
                    if (optTimer) clearTimeout(optTimer);
                }, function() {
                    optTimer = setTimeout(function() {
                        optHolder.hide();
                    }, 200);
                });
                selectBtn.click(function() {
                    if (optHolder.is(':visible')) {
                        optHolder.hide();
                    }
                    else {
                        optHolder.css({
                            top: replaced.offset().top + replaced.outerHeight(),
                            left: replaced.offset().left,
                            display: 'block'
                        });
                    }
                    return false;
                });
                select.addClass('outtaHere');
            }
        }
    });
}