var hoverTimer;
var interactionTimer;

jQuery(document).ready(function() {

    var usedNames = {};
    $J("select[name='diarySelector'] > option").each(function () {
        if(usedNames[this.text]) {
            $J(this).remove();
        } else {
            usedNames[this.text] = this.value;
        }
    });

    //Bold tour drop down
    var options = $J("select[id$='ToursByTypeDropDownList'] option").not(':selected');

    options.each(function(index) {

        if (!$J(this).hasClass("sub-type")) {
            $J(this).addClass("sub-type")
        }
    });
    // Extend Items 
    //========================================================================================================================================
    $J(".button-print a").click(function() {
        window.print();
    });

    // IE6 ToolTip hover
    $J("div.gallery div.media").hover(
        function() {
            $J(this).addClass("over");
        }, function() {
            $J(this).removeClass("over");
        });

    //Font size link in header
    //===========================================================//
    $J('.text-size a[title=Smaller]').click(function() {
        setActiveStyleSheet('regularText');
        $J(this).blur();
    });
    $J('.text-size a[title=Larger]').click(function() {
        setActiveStyleSheet('largeText');
        $J(this).blur();
    });

    // Carousel items
    //========================================================================================================================================
    if ($J('#tourDetails').length) {
        $J('#tourDetails').jcarousel({
            auto: 5,
            scroll: 1,
            vertical: true,
            wrap: 'last'
        });
    }

    // Form Element initialisation 
    //========================================================================================================================================
    if ($J(".custom-checkbox").length) {
        $J('.custom-checkbox input').customInput();
    }

    if ($J('select.custom-select').length) {
        $J('select.custom-select').selectmenu({ style: 'dropdown' });
    }

    if ($J("ul.feature-menu li div").length) {
        $J("ul.feature-menu li div").hover(
		  function() {
		      $J(this).addClass("hover");
		  },
		  function() {
		      $J(this).removeClass("hover");
		  }
		);
    }

    $J('input.clear, textarea.clear').addClass("");

    $J('input.clear, textarea.clear').focus(function() {
        $J(this).removeClass("idleField").addClass("focus");
        if (this.value == this.defaultValue) {
            this.value = '';
        }
        if (this.value != this.defaultValue) {
            this.select();
        }
    });

    $J('input.clear, textarea.clear').blur(function() {
        $J(this).removeClass("focus").addClass("");
        if ($J.trim(this.value) == '') {
            this.value = (this.defaultValue ? this.defaultValue : '');
        }
    });

    $J("ul.nav li.tours, ul.nav li div ul li, div.q-and-a h3").hover(
	  function() {
	      $J(this).addClass("hover");
	  },
	  function() {
	      $J(this).removeClass("hover");
	  }
	);

    $J('div.q-and-a h3').click(
		function() {
		    $J(this).next().toggle();
		    $J(this).toggleClass("active");
		    return false;
		}
	).filter(":not(.active)").next().hide();


    //Interactions panels
    //========================================================================================================================================
    var interactionButton = $J('.a-feature .feature-menu li');
    var interactionContent = $J('.a-feature .interactionGroup');
    var activeInteraction = $J(interactionButton)[0];

    //Initial active, could be any one
    var len = interactionButton.length;
    var temp = $J(interactionButton).children();
    for (var i = len; i--; ) {
        if ($J(temp[i]).hasClass('active')) {
            temp = i;
            continue;
        }
    }

    $J(interactionContent[temp]).css('display', 'block');
    $J(activeInteraction).css('color', '#000');

    if ($J('body.home').length) {
        //homepage auto cycle
        var initialCycle;
        var p = 0;
        initialCycle = setInterval(function() {
            p++;
            var tempInter;
            if (p < 4) {
                //iterate
                tempInter = $J('.a-feature .feature-menu li')[p];
            }
            else {
                //last cycle hardcode first 'default'
                tempInter = $J('.a-feature .feature-menu li')[0];
            }

            removeFromAll('.a-feature .feature-menu li div', 'active');
            removeFromAll('.a-feature .feature-menu li', 'active');

            $J(tempInter).addClass("active")
            $J(tempInter).children('div').addClass("active");

            // run animation
            interactionPanel(tempInter);
            if (p == 4) {
                clearInterval(initialCycle);
            }
        }, 3000);
    }

    //Hover action
    $J('.a-feature .feature-menu li').hover(function() {
        var featureTab = $J(this); ;

        clearInterval(initialCycle);
        clearTimeout(hoverTimer);

        hoverTimer = setTimeout(function() {
            clearTimeout(hoverTimer);
            removeFromAll('.a-feature .feature-menu li div', 'active');
            removeFromAll('.a-feature .feature-menu li', 'active');

            $J(featureTab).addClass("active");
            $J(featureTab).children("div").addClass("active");

            interactionPanel(featureTab);

        }, 150);

    }, function() {
        if ($J(this)[0] != $J(activeInteraction)[0]) {
            $J(this).css('color', '#008C9A');
        }
    });

    // Toggle slide for interactions panel ------------------
    $J('.toggle').toggle(
		function() {
		    var p = $J(this).parent();
		    p.animate({
		        width: '25'
		    }
			, function() {
			    p.addClass("minimised");
			});
		}, function() {
		    var p = $J(this).parent();
		    p.animate({
		        width: '325'
		    });
		    p.removeClass("minimised");
		});
    //========================================================================================================================================

    // Tour Inclusion - Tab Panel ------------------
    // load
    tabContent = $J('.panel-inclusions .inner div.content');
    $J(tabContent[getActiveClass('.panel-inclusions .menu a')]).addClass('active');

    // click
    $J('.panel-inclusions .menu a').click(function() {
        //menu 
        removeFromAll('.panel-inclusions .menu a', 'active');
        $J(this).addClass('active');

        // content
        removeFromAll('.panel-inclusions .inner div.content', 'active');
        $J(tabContent[getActiveClass('.panel-inclusions .menu a')]).addClass('active');
    });

    // Insert Videos --------------------------------
    if ($J('.insertVideoPlayer').length) {
        insertVideo('368', '323', '9');
    }

    // Photo Gallery -------------------------------
    $J('.gallery .media .showGallery').click(function() {
        $J('.gallery .media .more-link a').removeClass('active');

        $J(this).addClass('active');
        var item = getActiveClass('.gallery .media .more-link a');
        activateImage(item);
        tb_show('Gallery', '#TB_inline?height=550&width=630&modal=true&inlineId=gallery-overlay', false);
        return false;
    });

    //make image clickable
    $J('.gallery .media .image img').click(function() {
        $J(this).parents(".media").find(".more-link a").click();
    });

    $J('.gallery-overlay .close').click(function() {
        tb_remove();
        return false;
    });

    $J('.gallery-overlay .button-a').click(function() {
        var item = getActiveClass('.gallery-overlay .image img');
        var allImage = $J('.gallery-overlay .image img');

        allImage = allImage.length;
        item++;
        if (item >= allImage) {
            item = allImage - 1;
        }
        activateImage(item);
        return false;
    });

    $J('.gallery-overlay .button-c').click(function() {
        var item = getActiveClass('.gallery-overlay .image img');

        item--;
        if (item < 0) {
            item = 0;
        }
        activateImage(item);
        return false;
    });


    waterMark();

    //search
    $J("#search-link").click(function() {
        doSearch();
        return false;
    });

    $J("input.input-search").bind({
        keyup: function(event) {
            var code = (event.keyCode ? event.keyCode : event.which);
            if (code == 13)
                return $J("#search-link").click();
        }
    });

    $J("li[id$='listCss']").each(function() {
        $J(this).click(function() {
            var anchor = $J(this).find("div h2 a[id$='linkTitle']");

            if (anchor) {
                var url = anchor.attr("href");
                window.location = url;
            }
        });

    });


    //Photo Gallery Javascript
    $J(".gallery-selector").change(function() {
        if (this.value != "") {
            window.location = this.value;
        }
    });

    
});

function interactionPanel(location) {
    var interactionContent = $J('.a-feature .interactionGroup');
    var newActiveInd = getActiveClass($J('.a-feature .feature-menu li'));
    var location = location; 

    $J(location).css('color', '#000');

    clearTimeout(interactionTimer);
    interactionTimer = setTimeout(function() {
        
        //clearTimeout(interactionTimer);

        //Fade out current active stuff
        $J('.a-feature .feature-menu li div', location).stop().fadeTo(400, 0.0);
        $J(location).css('color', '#008C9A');
        $J(interactionContent).stop().fadeTo(200, 0.0).css({ zIndex: '4' });
        
        //Fade in current active stuff
        $J('.feature-menu li div').stop().fadeTo(400, 1.0);
        $J(interactionContent[newActiveInd]).stop().css({ opacity: '0', zIndex: '50' }).show().fadeTo(400, 1.0);

    }, 200);
}

function doSearch() {
    var searchTerm = $J("input.input-search").val();

    if (searchTerm.length == 0) {
        return;
    }

    if (searchTerm != $J("input.input-search").attr("title")) {
        var url = encodeURI($J("#search-link").attr("href").concat(searchTerm));
        window.location = url;
    }
}

function waterMark() {
    // clear hint on focus
    $J(".watermark").bind({
        focusin: function() {
            var formField = $J(this),
				formFieldVal = formField.val(),
				formFieldTitle = formField.attr("title");
            if (formFieldVal == formFieldTitle) {
                formField.val("");
            }
        },
        focusout: function() { // if empty string re-add hint
            var formField = $J(this),
				formFieldVal = formField.val(),
				formFieldTitle = formField.attr("title");

            if (formFieldVal == "") {
                formField.val(formFieldTitle);
            }
        }
    }).each(function(index, el) {
        if ($J(el).val() === "") {
            $J(el).val($J(el).attr("title"));
        }
    });
}

function activateImage(index) {
    var images = $J('.gallery-overlay .image img');
    $J(images).removeClass('active');
    $J(images[index]).addClass('active');
}

// return index of active class
function getActiveClass(searchParam) {
    var a = $J(searchParam);
    var l = a.length;
    for (i = l; i--; ) {
        if ($J(a[i]).hasClass('active')) {
            return i;
        };
    }
    return false;
}

// remove a class name from all items
function removeFromAll(searchParam, c) {
    var a = $J(searchParam);
    var l = a.length;
    for (i = l; i--; ) {
        $J(a[i]).removeClass(c);
    }
}

// Insert SWF into page
function insertVideo(width, height, flashPlayerVersion) {
    allVideos = $J('.insertVideoPlayer');
    for (i = 0; i < allVideos.length; i++) {
        myVideoContainer = $J(allVideos)[i];
        videoUrl = $J(myVideoContainer).attr('rel');
        videoId = $J(myVideoContainer).attr('id');
        insertHtml = "<script type='text/javascript'>"
                   + " var so = new SWFObject('/assets/video/player/videoPlayer.swf', 'mpl', '" + width + "', '" + height + "', '" + flashPlayerVersion + "');"
                   + " so.addParam('allowfullscreen', 'false'); "
                   + " so.addParam('allowscriptaccess', 'always'); "
                   + " so.addParam('wmode', 'opaque'); "
                   + " so.addVariable('fileName', '" + videoUrl + "'); "
				   + " so.addVariable('skinPath', '/assets/video/player/SteelOverAll.swf'); "
                   + " so.addVariable('autostart', 'false'); "
                   + " so.write('" + videoId + "'); "
                + " </script>";
        $J(myVideoContainer).after(insertHtml);
    }
}

//Limit char in Enuiry form
function limitText(limitField, limitNum) {
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    }
}
