/*******************************************************************************
 * all the things that have to be done on document load
 * requires JQuery 1.3 !!!!!!
 *
 * @return void
 ******************************************************************************/
$(function(){
    //try {getColorbox();		}catch (e) {}
    try {
        $("a[href*='output_adb_file']").live("click", function(){
            var href = $(this).attr('href');
            var pos = href.indexOf("agb=t");
            if (pos > 0) {
                window.open(this.href + "&popup=true&nav=" + _nav, "Download-Popup", "width=300,height=350,scrollbars=no");
                return false;
            }
        });
    } 
    catch (e) {
    }
    init();
});
// ready
$(document).ready(function(){
    try {
        $(document).pngFix({
            blankgif: '../../assets/common/z.gif',
            repeatMethod: 'Crop'
        });
    } 
    catch (e) {
    }
    try {
        setEventMonth();
    } 
    catch (e) {
        throwError(e);
    }
    try {
        getColorbox();
    } 
    catch (e) {
        throwError(e);
    }
    try {
        doAjaxAnmelden();
    } 
    catch (e) {
        throwError(e);
    }
    try {
        doAjaxSlider();
    } 
    catch (e) {
        throwError(e);
    }
}); // ende $(document).ready();
// init
function init(){
    try {
        getTagcloud();
    } 
    catch (e) {
        throwError(e);
    }
    try {
        getAutocompleteWords();
    } 
    catch (e) {
        throwError(e);
    }
    try {
        doAjaxLink();
    } 
    catch (e) {
        throwError(e);
    }
    // slider locationfinder
    try {
        getSliders();
    } 
    catch (e) {
        throwError(e);
    }
    try {
        getEventCoverflow();
    } 
    catch (e) {
        throwError(e);
    }
    try {
        getEventSlideshow();
    } 
    catch (e) {
        throwError(e);
    }
    try {
        getEventMonths();
    } 
    catch (e) {
        throwError(e);
    }
    // scroll fuer terminvorschau
    try {
        getDatesScroll();
    } 
    catch (e) {
        throwError(e);
    }
    try {
        getTooltip();
    } 
    catch (e) {
        throwError(e);
    }
    try {
        getLocationfinderSlider();
    } 
    catch (e) {
        throwError(e);
    }
    try {
        getGalleryview(false);
    } 
    catch (e) {
        throwError(e);
    }
    try {
        getDatePicker();
    } 
    catch (e) {
        throwError(e);
    }
    try {
        getGroundviewLocations();
    } 
    catch (e) {
        throwError(e);
    }
    try {
        getGroundviewBuilding();
    } 
    catch (e) {
        throwError(e);
    }
    try {
        $("#accordion").accordion({
            autoHeight: false,
            collapsible: true,
            icons: false
        }).accordion("activate", false);
    } 
    catch (e) {
        throwError(e);
    }
}

function getColorbox(){
    // colorbox
    $("a.colorbox").colorbox({
        //        height: "90%",
        //        width: "550px",
        onComplete: function(){
            var height = $('#cboxLoadedContent').height();
        }
    }, function(){
        //getGroundviewBuilding();
        getGalleryview(true);
        
        //var height = $('#cboxLoadedContent').height();
    });
    
    $("a.colorbox_groundview").colorbox({
        height: "90%",
        width: "500px",
        innerWidth: "460px",
        onComplete: function(){
            var height = $('#cboxLoadedContent').height();
        }
    }, function(){
        getGroundviewBuilding();
        
        //var height = $('#cboxLoadedContent').height();
    });
    
    
}

function setToolTips(){
    jQuery(".calHighlight").tooltip({
        extraClass: "activite"
    });
}

function getDatePicker(){
    $(".datepicker").datepicker({
        //yearRange: "1910:2010",
        //changeYear:true,
        dateFormat: "dd.mm.yy",
        dayNamesMin: ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"],
        monthNames: ['Januar', 'Februar', 'M&auml;rz', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember']
    });
    if ($('.calender').length != 0) {
        $('.tooltip').each(function(){
        
            if ($(this).find('.tooltip_content').length != 0) {
                $(this).qtip({
                    text: false,
                    content: $(this).find('.tooltip_content').html(),
                    hide: {
                        when: 'mouseout',
                        fixed: true
                    },
                    tip: 'bottomLeft'
                });
            }
        });
    }
}

function getTooltip(){
    // Notice the use of the each() method to acquire access to each elements attributes
    $('.tooltip').each(function(){
        $(this).qtip({
            text: false,
            hide: {
                when: 'mouseout',
                fixed: true
            },
            tip: 'bottomLeft'
        });
    });
    
}

function getAutocompleteWords(){
    var type = $(this).attr('name'); // name from input
    $('.suchtext').autocomplete({
        minLength: 2,
        search: function(){
            var params = $(this).parent('form').serialize();
            $(this).autocomplete("option", "source", getAjaxUrl('autocomplete&type=' + $(this).attr("name")) + '&' + params);
        },
        select: function(event, ui){
            log(ui.item ? ("Selected: " + ui.item.value + " aka " + ui.item.id) : "Nothing selected, input was " + this.value);
        }
    });
}

function getSliders(){
    var arrForms = ["form_people", "form_categories", "form_sqm"];
    
    $.each(arrForms, function(key, id){
        getSlider(id);
    });
    
    toggleSlider();
}

function getSlider(id){
    if ($('#' + id + ' select').length != 0) {
        $('#' + id + ' select').selectToUISlider({
            labels: 7,
            tooltip: false,
            labelSrc: 'text',
            sliderOptions: {
                change: function(e, ui){
                    doAjaxSlider();
                }
            }
        });
    }
}

function toggleSlider(){
    if ($('#form_categories select').val() == 11) {
        $("#locationslider2").show();
        $("#locationslider1").hide();
    }
    else {
        $("#locationslider1").show();
        $("#locationslider2").hide();
    }
}

function getLocationfinderSlider(){
    if ($('#locationfinder .result').length != 0) {
        $("#locationfinder .result").jCarouselLite({
            btnNext: "#locationfinder .next",
            btnPrev: "#locationfinder .prev",
            visible: 1,
            speed: 1400,
            vertical: true,
            auto: 1300
        });
    }
}

function getAjaxLoader(div){
    $(div).ajaxStart(function(){
        $(this).html('<div class="loading"></div>');
    });
}


function doAjaxAnmelden(){
    var params = {
        TOID: "freiburg_messe",
        VAC_PROFILE: "0", //Vakanzprofil
        LID: "0", // TP_Freiburg_Messe  Tracking Benutzer
        NAV: "1",
        LANG: "de"
    };
    var str_param = jQuery.param(params);
    
    // http://fit.tomas.travel/irs/TPortalRegion/start.jsp?TOID=freiburg_messe&MODULE=MOD_EXEC_VAC&VAC_PROFILE=0&LID=0&NAV=1&LANG=de&ARR_DAY=11&ARR_MONTH=5&ARR_YEAR=2010&NIGHTS=5&ADULTS=4&CITY=FIT00020070000008727
    $('.form_anmeldung_search .submit').click(function(){
        var form_params = $(this).parent('form').serializeArray();
        var datum = $(this).parent('form').find("input[name='datum']").val();
        var arr_datum = datum.split(".");
        var str_ort = $(this).parent('form').find("select[name='selPlace']").val();
        var str_pax = $(this).parent('form').find("select[name='selPax']").val();
        var str_nights = $(this).parent('form').find("select[name='selNights']").val();
        
        var form_params = {
            MODULE: "MOD_EXEC_VAC",
            ARR_DAY: ltrim(arr_datum[0], "0"),
            ARR_MONTH: ltrim(arr_datum[1], "0"),
            ARR_YEAR: arr_datum[2],
            NIGHTS: str_nights,
            ADULTS: str_pax,
            CITY: str_ort
        };
        var str = jQuery.param(form_params);
        var url = $(this).parent('form').attr('action') + str_param + "&" + str;
        $(this).colorbox({
            href: url,
            width: "700",
            height: "80%",
            iframe: true
        });
        
        return false;
    });
    
    $('.form_anmeldung_search .detailsuche').click(function(){
        var form_params = {
            MODULE: "MOD_VAC"
        };
        var str = jQuery.param(form_params);
        
        var url = $(this).parent('form').attr('action') + str_param + "&" + str;
        $(this).colorbox({
            href: url,
            width: "700",
            height: "80%",
            iframe: true
        });
        
        return false;
    });
    
}

function ltrim(str, charlist){
    // Strips whitespace from the beginning of a string
    //
    // version: 1004.2314
    // discuss at: http://phpjs.org/functions/ltrim    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Erkekjetter
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // *     example 1: ltrim('    Kevin van Zonneveld    ');    // *     returns 1: 'Kevin van Zonneveld    '
    charlist = !charlist ? ' \\s\u00A0' : (charlist + '').replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1');
    var re = new RegExp('^[' + charlist + ']+', 'g');
    return (str + '').replace(re, '');
}

function doAjaxSlider(){
    if ($('#locationfinder').length != 0) {
        getAjaxLoader("#locationfinder .result");
        
        toggleSlider();
        var category_id = $('#form_categories select').val();
        var people_id = 0
        var sqm_id = 0
        
        if ($('#locationslider1').is(":visible")) 
            var people_id = $('#form_people select').val();
        if ($('#locationslider2').is(":visible")) 
            var sqm_id = $('#form_sqm select').val();
        
        var url = $('#form_categories').attr('action');
        $.post(url, {
            sqm_id: sqm_id,
            people_id: people_id,
            category_id: category_id
        }, function(data){
            $("#locationfinder .result").html(data);
            
            if ($('#locationfinder .result ul').length != 0) {
                getLocationfinderSlider();
            }
        });
    }
}

function doAjaxLink(){
    $("a.ajax").click(function(){
        var url = $(this).attr("href");
        $.post(url, {}, function(data){
            eval(nl2empty(data));
        });
        return false;
    });
}

function getTagcloud(){
    /*
     $('#myCanvas').tagcanvas(
     {
     textColour : '#000000',
     outlineThickness : 1,
     maxSpeed : 0.03,
     depth : 0.75
     });
     return false;
     */
    if ($('#tagcloud').length != 0) {
        var html = $('#tagcloud').html();
        /*$('#tagcloud ul li').each(function()
         {
         html += $(this).html();
         });*/
        $('#tagcloud').html('');
        
        $('#tagcloud').flash({
            src: '../../assets/files/tagcloud.swf',
            width: 240,
            height: 300,
            wmode: 'opaque',
            flashvars: {
                tcolor: '0x666666',
                distr: 'true',
                tspeed: '110',
                xmlpath: html
                // mode: 'tags',
                // tagcloud: "<tags>" + html + "</tags>"
            }
        });
    }
}

function getEventCoverflow(){
    if ($('#event_coverflow').length != 0) {
        var slideshow = new ImageFlow();
        slideshow.init({
            startID: 3,
            ImageFlowID: 'event_coverflow',
            reflections: false,
            //aspectRatio: 1.9,
            imagesHeight: 0.9,
            imageFocusM: 1.9,
            //            imagesHeight: 2,
            //            imageFocusMax: 5.7,
            //            imageScaling: false,
            //            circular: true,
            //            buttons: true,
            //            opacity: false,
            //            imageCursor: 'pointer',
            //            sliderCursor: 'pointer',
            //            startAnimation: true,
            slider: false,
            captions: false,
            captionDivStyle: false
            //           xStep: 130
        });
        
        // default bild
        //debug($('#event_coverflow_logo img').attr('src').length);
        
        if ($('#event_coverflow_logo img').attr('src').length == 0) {
            var event_id = $('#event_coverflow_images img:eq(2)').attr('rel');
            if (event_id > 0) {
                $.ajax({
                    type: "GET",
                    url: getAjaxUrl('coverflow_img') + '&event_id=' + event_id,
                    dataType: "json",
                    success: function(msg){
                        if (msg.img_found == true){
                            $('#event_coverflow_logo img').attr('src', msg.img).attr('height', msg.height).attr('title', msg.title);
                            $('#event_coverflow_logo').fadeIn();
                        }
                    }
                });
            }
        }
        // logo laden
        $('#event_coverflow_images img').mouseover(function(){
            var event_id = $(this).attr('rel');
            if ($(this).attr('rel') > 0) {
                $.ajax({
                    type: "GET",
                    url: getAjaxUrl('coverflow_img') + '&event_id=' + event_id,
                    dataType: "json",
                    success: function(msg){
                        if (msg.img_found == true){
                            $('#event_coverflow_logo img').attr('src', msg.img).attr('height', msg.height).attr('title', msg.title);
                        }

                    }
                });
            }
        });
    }
}

function getEventSlideshow(){
    if ($('#event_slideshow .slider').length != 0) {
        $("#event_slideshow .slider").jCarouselLite({
            btnNext: "#event_slideshow .next",
            btnPrev: "#event_slideshow .prev",
            visible: 3,
            scroll: 2,
            speed: 1000
        });
    }
}

function getDatesScroll(){
    $('.date_pager .down').bind('mousedown mouseup', function(event){
        if (event.type == 'mousedown') {
            $('.dates_preview').animate({
                "scrollTop": "+=2000px"
            }, 3000, 'linear');
            return false;
        }
        else {
            $('.dates_preview').stop();
            return false;
        }
        
    });
    
    $('.date_pager .up').bind('mousedown mouseup', function(event){
        if (event.type == 'mousedown') {
            $('.dates_preview').animate({
                "scrollTop": "-=2000px"
            }, 3000, 'linear');
            return false;
        }
        else {
            $('.dates_preview').stop();
            return false;
        }
        
        return false;
    });
}


function setEventMonth(){
    var today = new Date();
    var month = today.getMonth() + 1;
    
    debug('month ' + month);
    debug('today ' + today);
    
    $("#event_months .months").ready(function(){
        $("#event_months .months").hide();
        if ($("#event_months #month-" + month + " ul").html()) {
            $("#event_months #month-" + month).fadeIn();
        }
        else { //also wenn keine Termine in dem aktuellen Monat vorhaden sind, rutsch zum nächsten mit Termine
            var bool = false;
            for (var i = 1; i <= 12 && !bool; i++) {
                if ($("#event_months #month-" + i + " ul").html()) {
                    $("#event_months #month-" + i).fadeIn();
                    bool = true;
                }
            }
            
            // Wenn garnicht gefunden wurde dann ersten Termin nehmen.
            if (i == 12 && !bool) {
                i = 1;
                $("#event_months #month-" + i).fadeIn();
            }
            
            
        }
        
        
    });
}

function getEventMonths(){
    if ($('#event_months').length != 0) {
        try {
            $("#event_months .months").show();
            
            $("#event_months ul#choose li a").click(function(){
                var month = $(this).attr("href").split("#"); //split the URL once
                month = month[1].split("-"); //then split the id that is send with the URL
                month = month[1]; //now assign the letter
                $("#event_months .months").hide();
                $("#event_months #month-" + month).fadeIn();
                return false;
            });
            $("#display-all-months").click(function(){
                $(".months").fadeIn();
                return false;
            });
        } 
        catch (e) {
        }
    }
}

function getGalleryview(colorbox){
    if ($('#galleryview').length != 0) {
        $('#galleryview').galleryView({
            filmstrip_size: 5,
            panel_width: 420,
            panel_height: 270,
            frame_width: 60,
            frame_height: 40,
            overlay_height: 50,
            img_path: '../../assets/jquery/plugins/galleryview/1.1/',
            img_path: '../../assets/common/',
            border: 'none',
            background_color: '#5b544c'
            //overlay_color: '#5b544c'
            //overlay_color: '#222',
            //overlay_text_color: 'white',
            //caption_text_color: '#222',
            //background_color: 'transparent',
            //nav_theme: 'dark',
            //pause_on_hover: true
        });
        $('#galleryview .nav-prev').attr('src', '../../assets/common/arrow_double_white_left.gif');
        $('#galleryview .nav-next').attr('src', '../../assets/common/arrow_double_white_right.gif');
        
        if (colorbox == true) {
            $.fn.colorbox.resize();
        }
        else {
            // Der Pointer darf nicht hier verwendet werden nur auf der Colorbox
            $('#galleryview #pointer').remove();
        }
        
    }
}

function getGroundviewLocations(){
    //$('.overview .button').click(function(){
    //$('.overview').toggle();
    //return false;
    //});
    
    debug('++++++++++');
    
    $("#accordion_receiver img").hide();
    $("#accordion_receiver img").first().show();
    if ($('#new_accordion').length != 0) {
        $('.accordion-links a.intern').click(function(){
            var href = $(this).attr('id').split("_");
            var asset_id = href[2]; //split the URL once
            var img_id = 'overview_img_' + asset_id;
            
            debug('*****');
            
            if ($('#' + img_id).length != 0) {
                $("#accordion_receiver img").hide();
                $('#' + img_id).show();
            }
            return false;
        });
    }

    $('#new_accordion h3 a').click(function(){
        $(this).find('.arrow').toggleClass('arrow_open');
        
//        $('#new_accordion ul').hide();
        $(this).parent().next('ul').toggle('slow');
        return false;
    });
}

function getGroundviewBuilding(){
    if ($('.map').length != 0) {
        $('img.map').maphilight({
            fill: true,
            fillColor: '9db9c9',
            fillOpacity: 0.8,
            stroke: false,
            strokeColor: 'ff0000',
            strokeOpacity: 1,
            strokeWidth: 1,
            fade: false,
            alwaysOn: false
        });
        
        var html = $('#description_box').html();
        
        $('area').mouseover(function(){
            var href = $(this).attr('href').split("#");
            var id_div = '#' + href[1];
            $('#description_box').html('');
            $(id_div).clone().appendTo('#description_box');
            //		 $('#description_box').html($(id_div).clone().html());
        
            //$.fn.colorbox.resize();
        
        }).mouseout(function(){
            //$('#description_box').html(html);
        });
        
    }
}

function str_replace(search, replace, subject){
    return subject.split(search).join(replace);
}

function nl2empty(str){
    if (typeof(str) == "string") 
        return str.replace(/(\r\n)|(\n\r)|\r|\n/g, "");
    else 
        return str;
}

function debug(error){
    if (window.console) {
        console.debug(error);
    }
}

function throwError(e){
    debug(e);
}

function openpopup2(url) {//PopUp
	  open(url,'popup',  'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,copyhistory=no,width=620,height=600');
}

function check(id)
{
  $('#' + id).attr('checked','checked');
}

