/**
 * DEUTSCHEREISE
 *
 * @package     custom.js
 * @author      M. Hatzfeld
 * @copyright   Copyright (c) 2010 ReiseClubD Gmbh & Co. KG
 * 
 * Last Update:
 * 02.12.2011 (mh) - modified teaser slider (faster slides)
 *
 * 11.08.2011 (mh) - modified tooltip function: prevent default link action
 *
 * 16.06.2011 (mh) - added info text for input fields function
 * 
 * 07.06.2011 (mh) - extended hotelinfo tab action
 * 
 * 06.06.2011 (mh) - added toggle function to accordion class (jq accordion is NOT used)
 *                 - added hotelInfoAlternative function
 *		
 */
$(document).ready(function()
{
	
    initMainNavi();
    inputVal();
	
    // scroll to top on request
    scrollToTop("a#totop");

    // Tabs load
    if($('.tabs').length > 0) {
        initTabs();
    }
	
    // Remote Tabs load
    if($('.remote-tabs').length > 0) {
        remoteTabs();
    }
	
    // Author Div
    if($('.toggle-author-div').length > 0) {
        authorToggler();
    }
	
    // Rounded Corner Image
    if($('img.box-image').length > 0) {
        roundedImageCorners();
    }
    
    // Content Toggle
    $('.accordion .slide').click(function() {
	$(this).next().toggle(0);
	return false;
    }).next().hide();
	

	/*  Hotelinfo Tabs actions
	 *  
	 *  
	 *  Just load the hotel info iframe when the user
	 *  clicked on the info button. 
	 */  
	$('.env-map-tab').click(function(){

		// Getting Giata ID
		var gid = $(this).parent().parent().parent().parent().attr('id');
		gid = gid.substr(11);

		// Getting iframe link
		var ref = $('#env-map-cont' + gid + ' a').attr('href');

		// Set source for iframe
		if($('#env-map-cont' + gid + ' iframe').attr('src') != ref)
		{
			$('#env-map-cont' + gid + ' iframe').attr('src', ref);
		}
	});
	
	$('.env-info-tab').click(function(){

		// Getting Giata ID
		var gid = $(this).parent().parent().parent().parent().attr('id');
		gid = gid.substr(11);

		// Getting iframe link
		var ref = $('#env-info-cont' + gid + ' a').attr('href');

		// Set source for iframe
		$('#env-info-cont' + gid + ' iframe').attr('src', ref);		
	});
	
	// Show alternative description (hotelinfo)
	$('.hotel-info-alt').click(function(){

		// Getting Giata ID
		var gid = $(this).parent().parent().parent().parent().parent().attr('id');
		gid = gid.substr(11);

		// Getting iframe link
		var ref = $(this).attr('title');

		// Set source for iframe
		$('#hotel-desc-cont' + gid).hide();
		$('#env-info-cont' + gid).show();
		$('#env-info-cont' + gid + ' iframe').attr('src', ref);		
	});
	
	
	
    //Youtube-Video Fancybox
    $("a.video-fancybox").click(function() {
        $.fancybox({
            'padding'		: 0,
            'autoScale'		: false,
            'transitionIn'	: 'none',
            'transitionOut'	: 'none',
            'title'			: this.title,
            'width'			: 640,
            'height'		: 385,
            'href'			: this.href = this.href.replace(new RegExp("watch\\?v=", "i"), 'v/') + '&autoplay=1',
            'type'			: 'swf',
            'swf'			: {
                'allowfullscreen':'true'
            }
        });
        return false;
    });
	
    // std fancybox
    if($("a.fancybox").length > 0)
        $("a.fancybox").fancybox();
	
    // click to zoom label
    if($("a.fancybox.zoom").length > 0) {
        $("a.fancybox.zoom").each(function() {
            $(this).find('img').after('<span class="ico ico-zoom">Vergrößern</span>');
        });
    }
	
    // terms link
    if($("a.tooltip").length > 0) {
        $('a.tooltip').click(function(e) {
            e.preventDefault();
        });
        $("a.tooltip").hover(function(e) {
			
            xOffset = 10;
            yOffset = 60;
			
            var href = $(this).attr('href');
            var c = $(href).html();
            this.t = this.title;
            this.title = '';
			
            //Append the tooltip template and its value
            $('body').append('<div id="tip" class="dr-tip corners"><strong class="tip-head corners-top">' + this.t + '</strong><div class="tip-content">' + c + '</div></div>');
			
            //Set the X and Y axis of the tooltip
            $('#tip')
            .css('top', (e.pageY - yOffset) + 'px')
            .css('left', (e.pageX - xOffset) + 'px')
            .fadeIn('fast');
        },
        function(){
            //Remove the appended tooltip template
            this.title = this.t;
            $('#tip').remove();
        });
		
        $("a.tooltip").mousemove(function(e){
            $("#tip")
            .css("top",(e.pageY - yOffset) + "px")
            .css("left",(e.pageX + xOffset) + "px");
        });
    }
	
    // Main Teaser
    if($('#dr-slider').length > 0)
    {
        $('#dr-slider').cycle({
            fx: 'fade',
            speed: 700,
            timeout: 4500,
            pager: '#pager',
            pagerAnchorBuilder: buildPagination,
            easing: 'easeInOutCubic',
            pause: true,
            next: '#next',
            prev: '#prev'
        });
		
        $('#dr-slider').find('.dr-slider-desc').fadeIn();
        $('#dr-slider').find('.link-box').fadeIn();
		
    }
	
    // Main Teaser: Quicksearch
    if($('#quicksearch').length > 0)
    {
        var title = $('#quicksearch-title').find('strong');
			
        $("#quicksearch").find('.tabs-nav a').hover(function()
        {
            title.text($(this).text());
        },
        function()
        {
            title.text($(this).offsetParent().find('.selected').text());
        });
    }
	
    // Content Carousel
    if($('.carousell .carousell-wrapper').length > 0)
    {
        $(".carousell .carousell-wrapper").each(function(){
            $(this).jCarouselLite({
                btnNext: ".next",
                btnPrev: ".prev",
                visible: 4
            });
   		
            var h = $(this).height();
   		
            $('.carousell .next').css('height', h-2);
            $('.carousell .prev').css('height', h-2);
        });
    }
    	

    /* Show more content
	 * eg: 	<a href="#target" class="showMore">Mehr anzeigen</a>
	 *		<div id="target">Show me on click at the .showMore link.</div>	 *
	*/
    $('.toggle').click(function() {
        var stdTxt = $(this).text();
        var ttlTxt = $(this).attr('title');

        $(this).toggleClass('open');

        $( $(this).attr('rel') ).slideToggle('slow', function() {
            $( this ).css('height', $( this ).height() + 'px');
        });
        $(this).text($(this).text() == ttlTxt ? 'Ausblenden' : ttlTxt);
        return false;
    });



    $("a.ico-regInf, .htlInfo a.ico-regInfo, .htlName a, .htlDesc p a, .slideToggle .close").click(function () {

        var idelem = $(this).attr('rel');
        


        if( $('#toggleCont_' + idelem).is(':hidden') )
        {
            $('.slideToggle').css('display', 'none'); 
            $("ul.tabs-nav li").removeClass("selected");
        }

        $('#toggleCont_' + idelem).slideToggle(100);
        
        if($('.tabs').length > 0) {
            $(".tabs-content"+idelem).hide(); // Hide all contents
            $("ul.tabs-nav.nvT"+idelem+" li:first").addClass("selected"); //Activate first tab
            $(".tabs-content"+idelem+":first").show(); //Show first tab content

            //On Click Event
            $("ul.tabs-nav li a").click(function()
            {
                $("ul.tabs-nav li").removeClass("selected"); //Remove any "active" class
                $(this).parent().addClass("selected"); //Add "active" class to selected tab
                $(".tabs-content"+idelem).hide(); //Hide all tab content

                var activeTab = $(this).attr("href");
                $(activeTab).show();
                return false;
            });
        }
        return false;
    });


	// Toggle Valuations content
    $("a.vltnLink").click(function () {
		var idelem = $(this).attr('rel');
        $('#toggleVltn_' + idelem).slideToggle(100);
    });

    /* Show region info	*/
    /* TODO: Regionsinfos Toggler überarbeiten!!! */
    $('.bookingTblDstntn .regInfo').click(function() {

        var visibleState = true;

        $('.regInfo')
        .html('<span class="bkngSprite ico-regInfo"></span>Regionsinfos anzeigen')
        .removeClass('open')
        .parent()
        .parent()
        .removeClass('regOpen')

        $('.regInfoWrapper')
        .slideUp('fast')
        .remove().css("visibility", 'hidden');
 
        $(this)
        .html($(this).html() ==
            '<span class="bkngSprite ico-regInfo"></span>Regionsinfos anzeigen' ?
            '<span class="bkngSprite ico-regInfo"></span>Regionsinfos schließen' :
            '<span class="bkngSprite ico-regInfo"></span>Regionsinfos anzeigen');

        $(this).toggleClass('open');
            
        $(this)
        .parent()
        .parent()
        .addClass('regOpen');

        $('<tr class="regInfoWrapper"><td colspan="5">asdasd</td></tr>')
        .insertAfter('.regOpen');

        return false;
    });


    /* user search Query */
    $('.userQuery').find('.close').click(function()
    {
        $(this).parent().parent().fadeOut();
        return false;
    }
    );

    // Load dialog on click
    $('.modal').click(function (e) {
        $( $(this).attr('rel') ).modal({
            minHeight:300,
            minWidth:300
        });

        return false;
    });

    // Display an external page using an iframe
    $('.modal-external').click(function (e) {
        var src = $(this).attr('rel');
        $.modal('<iframe src="' + src + '" height="780" width="1110" style="border:0" />', {
            closeHTML:"",
            containerCss:{
                backgroundColor:"#fff",
                borderColor:"#fff",
                height:780,
                padding:0,
                width:999
            },
            overlayClose:true
        });
    });

    swapValue = [];
    $("input.rplVl").each(function(i){
        swapValue[i] = $(this).val();
        $(this).focus(function(){
            if ($(this).val() == swapValue[i]) {
                $(this).val("");
            }
            $(this).addClass("focus");
        }).blur(function(){
            if ($.trim($(this).val()) == "") {
                $(this).val(swapValue[i]);
                $(this).removeClass("focus");
            }
        });
    });

    /* payment method content */
    if ( $('#pymnt').length > 0 ) {       
        $('#pymnt').find("input:radio[name='payment']").click(function() {
            $( '#pymnt' ).find('div').hide();
            $( '#pymnt_' + $("input:radio:checked[name='payment']").val() ).fadeIn('fast');
        });

        var p1 = $("#payment1:checked").val();
        var p2 = $("#payment2:checked").val();
        var p3 = $("#payment3:checked").val();

        if ( p1 == 1 || p2 == 2 || p3 == 3) {
            $( '#pymnt' ).find('div').hide();
            
            if( p1 == 1)
                $( '#pymnt_1' ).fadeIn('fast');

            if( p2 == 2)
                $( '#pymnt_2' ).fadeIn('fast');

            if( p3 == 3)
                $( '#pymnt_3' ).fadeIn('fast');
        }
    }
});

    //changes value of destination, if trigger is changed. 
    //  destination is only changed, if it is empty or if it matches the old value of trigger
    function changeValueIfEmptyOrEqual(trigger, destination)
    {
        trigger.focus(function(){
            trigger.data('oldVal', trigger.val());
        });  

        trigger.change(function() 
        {
            if(destination.val() == '' || trigger.data('oldVal') == destination.val())
            {
                destination.val(trigger.val());
            }
        });
    }
    
    function calculateAge(oDate)
    {
        if (isNaN(oDate.getYear()))
        {
            return '';
        }
        
        var curDate  = new Date();
        var age      = curDate.getFullYear() - oDate.getFullYear();

        if (curDate.getMonth() < (oDate.getMonth()))
        {
            age--;
        }
        
        if ((oDate.getMonth() == curDate.getMonth()) && (curDate.getDate() < oDate.getDate()))
        { 
            age--;
        }

        return age;
    }


// Main Navi
function initMainNavi()
{
    $(" #nav ul ").css(
    {
        display: "none"
    }); // Opera Fix
	
    $(" #nav li").hoverIntent(function()
    {
        $(this).addClass('over').find('ul:first').show();
    },function()
    {
        $(this).removeClass('over').find('ul:first').fadeOut('fast');
    });

}


// init Tabs
function initTabs()
{
    $(".tabs-content").hide(); //Hide all content
    $("ul.tabs-nav li:first").addClass("selected").show(); //Activate first tab
    $(".tabs-content:first").show(); //Show first tab conten
		
    //On Click Event
    $("ul.tabs-nav li a").click(function()
    {
        $("ul.tabs-nav li").removeClass("selected"); //Remove any "active" class
        $(this).parent().addClass("selected"); //Add "active" class to selected tab
        $(".tabs-content").hide(); //Hide all tab content

        var activeTab = $(this).attr("href");
        $(activeTab).fadeIn('fast');
        return false;
    });

//var $tabs = $(".tabs").tabs({fx: { opacity: 'toggle', remote: false  }});

}


// Remote Tabs
function remoteTabs()
{

    // Tabs
    //When page loads...
    $(".tab-content").hide();
    $("ul.tab-nav li:first").addClass("current").show();
    $(".tab-content:first").show();
    $(".tab-content:first").html('<span id="tab-loader" class="loader">');

    $.get($('ul.tab-nav li:first a').attr("href"), function(data) {
        $('.tab-content:first').html(data);
        $('#tab-loader').fadeOut();
    });

    //On Click Event
    $("ul.tab-nav li a").click(function() {

        $("ul.tab-nav li").removeClass("current");
        $(this).parent().addClass("current");
        $(".tab-content").hide();

        var target = $(this).offsetParent().find('.tab-content');
		
        $(target).fadeIn();

        $(target).html('<span id="tab-loader" class="loader">');
		
        $.get(
            $(this).attr("href"),
            function(data)
            {
                $(target).html(data);
                $('#tab-loader').fadeOut();
                $(this).parent().addClass('current');
            }
            );

        return false;
	
    });
		
}


// init input
function inputVal(){
    swapValue = [];
    $("input.input-text").each(function(i){
        swapValue[i] = $(this).val();
        $(this).focus(function(){
            if($(this).val() == swapValue[i]) {
                $(this).val("");
            }
            $(this).addClass("focus");
        }).blur(function(){
            if ($.trim($(this).val()) == "") {
                $(this).val(swapValue[i]);
                $(this).removeClass("focus");
            }
        });
    });
}

// Cycle: Pagination
function buildPagination(i, elem){
    var num = i+1;
    var title = $(elem).find('h2').text();
    var html = '<a href="#" title="' + title + '">' + num + '</a>';
    return html;
}


function authorToggler(){

    $('.toggle-author-div').click(
        function(){
            var href = $(this).attr('href');
            $(href).fadeIn();
            return false;
        }
        );
	
    $('.myauthor').find('.close').click(function()
    {
        $(this).parent().parent().fadeOut();
        return false;
    }
    );
	
}

/* Scroll To Top - scroll window to the top
=================================================================================================== */
function scrollToTop (e) {
    // Build toTopLink
    $('body').append('<a href="#" id="totop" class="arr-t" title="nach oben">nach oben</a>');
	
    $(e).hide().removeAttr("href");
    if ($(window).scrollTop() != "0") {
        $(e).fadeIn("slow")
    }
    var scrollDiv = $(e);
    $(window).scroll(function () {
        if ($(window).scrollTop() == "0") {
            $(scrollDiv).fadeOut("slow")
        } else {
            $(scrollDiv).fadeIn("slow")
        }
    });
    $(e).click(function () {
        $("html, body").animate({
            scrollTop: 0
        }, "slow")
    })
}


/* Rounded Image Corners
=================================================================================================== */
function roundedImageCorners(){
    $('img.box-image').one('load',function () {
        var img = $(this);
        var img_width = img.width();
        var img_height = img.height();
 
        // build wrapper
        var wrapper = $('<div class="rounded_wrapper"></div>');
        wrapper.width(img_width);
        wrapper.height(img_height);
 
        // move CSS properties from img to wrapper
        wrapper.css('float', img.css('float'));
        img.css('float', 'none')
 
        wrapper.css('margin-right', img.css('margin-right'));
        img.css('margin-right', '0')
 
        wrapper.css('margin-left', img.css('margin-left'));
        img.css('margin-left', '0')
 
        wrapper.css('margin-bottom', img.css('margin-bottom'));
        img.css('margin-bottom', '0')
 
        wrapper.css('margin-top', img.css('margin-top'));
        img.css('margin-top', '0')
 
        wrapper.css('display', 'block');
        img.css('display', 'block')
  
        // wrap image
        img.wrap(wrapper);
 
        // add rounded corners
        img.after('<div class="tl"></div>');
        img.after('<div class="tr"></div>');
        img.after('<div class="bl"></div>');
        img.after('<div class="br"></div>');
    }).each(function() {
        if(this.complete) $(this).trigger("load");
    });
}



function openbox(url)
{
    var infowin = window.open(url,"Bedingungen","width=700,height=600,scrollbars=yes,toolbar=no");
    infowin.focus();
}

/* info text for form fields show/hide onclick action
=================================================================================================== */

// focus/blur logic for form field to hide and show the info text.
// can't use rplVl function  because that will clear the input field on focus,
// if you send the form and got a wrong/invalid email-adresses in your input field, too.
function inputHint(inputName, inputStr)
{
	if($('input[name=' + inputName + ']').val() == '')
	{
		$('input[name=' + inputName + ']').val(inputStr);
		$('input[name=' + inputName + ']').addClass('defaultvl')
	}

	$('input[name=' + inputName + ']').focus(function(){

		if($(this).val() == inputStr)
		{
			$(this).val('');
		}
	});

	$('#formFilter').submit(function() {
		if($('input[name=' + inputName + ']').val() == inputStr)
		{
			$('input[name=' + inputName + ']').val('');
		}
	});
}



// focus/blur logic for form field to hide and show the info text.
// can't use rplVl function  because that will clear the input field on focus,
// if you send the form and got a wrong/invalid email-adresses in your input field, too.
function inputHintArea(id, inputStr)
{
    var obj = $('#'+ id);

        if(obj.text() == '')
        {
                obj.text(inputStr);
                obj.addClass('defaultvl')
        }

        obj.focus(function(){

                if($(this).text() == inputStr)
                {
                        $(this).text('');
                }
        });

        $('#bf').submit(function() {
                if(obj.text() == inputStr)
                {
                        obj.text('');
                }
        });
}
