/**
 * Widget login
 */
var fixedContentTimeout = false;

/**
 * Load default layout functionality when DOM is loaded
 */
$(document).ready(function() {
    
    pingSession();
  
    // load formular custom select
    comboBox();
    flyOutMenu();
    
    $(window).resize(function() {
      $.each(allUIMenus, function(i){
          if (allUIMenus[i].menuOpen) {
              allUIMenus[i].kill();
          };	
      });

      if( $('#main-navigation').find('.active') )
        $('#main-navigation').find('.active').removeClass('deactive');
    });
});

// ping session every 5 minutes
function pingSession() {
  var timerName = '$pingSessionTimerID', 
      timerID = $(document).data(timerName);
  if( timerID !== undefined )
    clearTimeout(timerID);
  
  timerID = setTimeout(function() {
    $.get('cms/ajax/ajaxAPI.php', {'ping':'session'}).success(function() {
      pingSession();
    });
  }, '300000'); // 5 minutes
  $(document).data(timerName, timerID);
};

function zoomMedia(id, width, height)
{
    width = width+46;
    height = height+50;

    // wenn der dialog noch nicht erstellt wurde
    if($("#media_zoom").length == 0)
    {
        $("body").append("<div id=\"media_zoom\"></div>");
        $("#media_zoom").dialog({
            width: width,
            height: height,
            resizable: false,
            modal:true,
            position: ['center', 20],
            open: function()
            {
                projectTheme(this);
            }
        });
    }

    AjaxAPI('CoreDialog', 'getMediaZoom', {
        mediaID:id
    }, function(response)
    {
        $("#media_zoom").html(response);
        $("#media_zoom").dialog("open");
        
        if($("#media_zoom .zreel").length > 0)
        {
          window.setTimeout(function() {
            $('#media_zoom').css({'text-align':'center'});
            initReel();
          },250);
        }
        
        flowplayer(".mediacenterEdit_flowplayer", "cms/theme/js/flowplayer/flowplayer-3.2.7.swf", {
            plugins:  {
                controls: {
               
            }
            },
            clip: {
                scaling: "orig"
            }
        });
    });
}

function showGallery(id)
{

    // wenn der dialog noch nicht erstellt wurde
    if($("#media_zoom_gallery").length == 0)
    {
        $("body").append("<div id=\"media_zoom_gallery\" style=\"background-color:#fff;\"></div>");
        $("#media_zoom_gallery").dialog({
            width: 900,
            resizable: false,
            modal:true,
            position: ['center', 20],
            open: function()
            {
                projectTheme(this);
            }
        });
    }

    AjaxAPI('CoreDialog', 'showGallery', {
        mediaID:id
    }, function(response)

    {
        $("#media_zoom_gallery").html(response);
        $("#media_zoom_gallery").dialog("open");
        activateGalleryScrollZoom();
        flowplayer(".mediacenterEdit_flowplayer", "cms/theme/js/flowplayer/flowplayer-3.2.7.swf", {
            plugins:  {
                controls: null
            },
            clip: {
                scaling: "fit"
            }
        });
    });
}

function activateGalleryScrollZoom()
{
    if($("#media_zoom_gallery .scrollable").find("img").size() >= settings.numItemsShowScrollableZoom)
    {
        $("#media_zoom_gallery .scrollable").scrollable();
    }
    else
    {
        $("#media_zoom_gallery .scrollable").prev().fadeTo('fast', 0.0);
        $("#media_zoom_gallery .scrollable").next().fadeTo('fast', 0.0);
    }

    $("#media_zoom_gallery .items img").click(function() {

        // see if same thumb is being clicked
        if ($(this).hasClass("active")) {
            return;
        }

        var url = $(this).attr("src").replace(galleryZoomPreviewItemSuffix, "_zoom.");

        // get handle to element that wraps the image and make it semi-transparent
        var wrap = $("#image_wrap").fadeTo("medium", 0.5);

        var img = new Image();


        // call this function after it's loaded
        img.onload = function() {

            // make wrapper fully visible
            wrap.fadeTo("fast", 1);

            // change the image
            wrap.find("img").attr("src", url);

        };

        img.src = url;

        // activate item
        $("#media_zoom_gallery .items img").removeClass("active");
        $(this).addClass("active");

    // when page loads simulate a "click" on the first image
    }).filter(":first").click();
}

function activateGalleryScroll()
{
    $(".mediaitem_scrollable").each(function(index, el)
    {
        if($(this).find("img").size() >= settings.numItemsShowScrollable)
        {
            $(this).scrollable();
        }
        else
        {
            $(this).prev().fadeTo('fast', 0.0);
            $(this).next().fadeTo('fast', 0.0);
        }
    });

    $(".mediaitem_scrollable .items img").click(function() {

        // see if same thumb is being clicked
        if ($(this).hasClass("active")) {
            return;
        }

        var url = $(this).attr("src").replace(galleryFrontendPreviewItemSuffix, "_big.");

        var galleryID = $(this).attr('alt').replace(/gallery_/, '');

        // get handle to element that wraps the image and make it semi-transparent
        var wrap = $("#image_wrap_"+galleryID).fadeTo("medium", 0.5);

        var img = new Image();


        // call this function after it's loaded
        img.onload = function() {

            // make wrapper fully visible
            wrap.fadeTo("fast", 1);

            // change the image
            wrap.find("img").attr("src", url);

        };

        img.src = url;

        // activate item
        $(".mediaitem_scrollable .items.gallery_"+galleryID+" img").removeClass("active");
        $(this).addClass("active");

    // when page loads simulate a "click" on the first image
    });
}

function activateGalleryScrollVisual()
{
    if($(".visual_scroll_products").length > 0)
    {
        $(".visual_scroll_products").scrollable(
        {
            circular: true,
            speed:1000
        });
        
        $(".pics img").each(function(){
           $(this).dropShadow({opacity: 0.3, left:0});
        });
        
    }
    else
    {
        $(".visual_scroll").scrollable(
        {
            next: '.thereWillNeverBeAClassLikeThisNext',
            prev: '.thereWillNeverBeAClassLikeThisPrev',
            circular: true,
            speed:1000
        });
        if(fixedContentTimeout === false)
            window.setTimeout("visualScrollSeekToNext()", 5000);
    }
}

function visualScrollSeekToNext()
{
    return false;
    fixedContentTimeout = true;
    if($(".visual_scroll .pics div").length > 0)
    {
        $(".visual_scroll").data("scrollable").next();
        window.setTimeout("visualScrollSeekToNext()", 5000);
    }
    else
    {
        fixedContentTimeout = false;
    }
}

$(document).ready(function()
{
    $(".formular_slider").each(function()
    {
        var id = $(this).attr('id');
        var min = $("#"+$(this).attr('id')+"_min").val();
        var value = $("#"+$(this).attr('id')+"_value").val();
        var max = $("#"+$(this).attr('id')+"_max").val();
        var step = $("#"+$(this).attr('id')+"_step").val();
        
        var showAmount = $(this).attr('id')+"_value";
        
        $(this).slider({
            value: value,
            min: min,
            max: max,
            step: step,
            slide: function( event, ui ) {
                $("#"+showAmount).val( "$" + ui.value );
            }
        });
    });
});

function comboBox() {
    if( $(".combobox") ) {
        $( ".combobox" ).combobox();
        $( "#toggle" ).click(function() {
            $( "#combobox" ).toggle();
        });
    }
}


function loginSubmitOnEnter(myfield,e) {
//  var keycode;
//  if (window.event) keycode = window.event.keyCode;
//  else if (e) keycode = e.which;
//  else
//    return true;
//
//  if (keycode == 13) {
//     myfield.form.submit();
//     return false;
//  }
//  else
//     return true;
}

function initFlowPlayerInstances()
{   
    initFlowPlayerVisual(); 
    
    initFlowPlayerModules();
    
    initFlowPlayerAudio();
   
   /*
    $f("*").each(function()
    {
        console.log($(this.getParent()).attr('class'));
        if($(this.getParent()).attr('id').indexOf("visual") > 0)
            this.play(); 
        else
            this.load();
    });
    */
}

function initFlowPlayerAudio()
{
    $(".audioplayer").each(function()
    {   
        var url = $(this).attr('alt');
        var flowplayerID = $(this).attr('id');
        var imageURL = $(this).children().attr('src');
        
        flowplayer(flowplayerID, {src: "cms/theme/js/flowplayer/flowplayer-3.2.7.swf"}, {
            clip: {
		// our song
                url: url,
                coverImage: { url: imageURL, scaling: 'orig'}
            },
            onBeforeFinish: function()
            {
                
            },
            play:{opacity:0}
        });
    });
}

function initFlowPlayerVisual()
{
    
    if($("#flowplayer-visual").length > 0)
    {   
        $("#flowplayer-visual").fadeTo("fast", 0.0);
        
        // visual instance
        flowplayer("flowplayer-visual", {src: "cms/theme/js/flowplayer/flowplayer-3.2.7.swf", wmode: "opaque"}, {
            plugins:  {
                controls:null
            },
            play: {opacity:0},
            onBeforeFinish: function()
            {
                return false;
            },
            clip: {
                scaling: "scale",
                bufferLength: 1,
                autoPlay: true,
                autoBuffering: true,
                onBufferFull: function()
                {   
                    
                },
                onStart: function()
                {
                    $("#flowplayer-visual").fadeTo("fast", 1);
                    //$("#flowplayer-visual").css("z-index", 1);
                    //hideFlowPlayerPreloadContainer(".content_fixed_visual_preload");
                },
                onBeforeOnload: function()
                {
                 
                }
            },
            canvas: {
                backgroundColor: '#c50922',
                backgroundGradient: 'none'

            }
        }).ipad({
            
        });
       
        if($("#flowplayer-visual-preload").length > 0)
        {
            
            /*
            // visual preload instance
            flowplayer("flowplayer-visual-preload", "cms/theme/js/flowplayer/flowplayer-3.2.7.swf", {
                plugins:  {
                    controls:null
                },
                onBeforeFinish: function()
                {
                    return false;
                },
                clip: {
                    scaling: "fit",
                    bufferLength: 3,
                    autoPlay: true,
                    autoBuffering: true
                }
            }).ipad();
            */
        }
    }
}

function hideFlowPlayerPreloadContainer(preloadContainer)
{
    if($(preloadContainer).length > 0)
        $(preloadContainer).hide();
}

function initFlowPlayerModules()
{    
    var bufferingStopped = new Array();
    
    // player instance
    $(".flowplayer-modules").each(function()
    {
        var flowplayerModuleID = $(this).attr('id');
        
        var playlist = new Array();
        
        if($("#"+flowplayerModuleID+"-preload").length > 0)
            playlist = new Array( $("#"+flowplayerModuleID+"-preload").val(), $(this).attr('href') );
        else
            playlist = new Array($(this).attr('href'));
        
        bufferingStopped[flowplayerModuleID] = false;
        
        flowplayer(flowplayerModuleID, "cms/theme/js/flowplayer/flowplayer-3.2.7.swf", {
            playlist: playlist,
            clip: {
                scaling: "fit",
                bufferLength: 3,
                autoPlay: true,
                autoBuffering: true,
                onStart: function()
                {   
                    if (bufferingStopped[flowplayerModuleID]) return;
                    this.stopBuffering();
                    this.stop();
                    this.pause();
                    bufferingStopped[flowplayerModuleID] = true; 
                },
                onStop: function()
                {
                 
                },
                onFinish: function()
                {
                 
                }
            },
            onStart: function()
            {   
            
            }
        });
    });
}

$(document).ready(function() {

    var actualFontSize = "1";
    var fontSizeDiff = 0;
    var fontSizeInterval = 1;

    activateFAQ();
    activateEvents();

    initFlowPlayerInstances();

    $("#dialog-safetycode").dialog({
        modal:true,
        autoOpen: false,
        resizable: false,
        draggable: false,
        width:500,
        open: function()
        {
            projectTheme(this);
        }
    });


    // schriftgröße
    $(".fontsize").click(function(){

        // newFontSize
        var newFontSize = $(this).attr('id').replace(/fontsize-/, '');

        // Fontsize Difference
        fontSizeDiff = newFontSize - actualFontSize;

        // neue Größe speichern
        actualFontSize = newFontSize;

        // elemente
        var elements = new Array();
      
        // fontsize hat sich geändert
        if(fontSizeDiff != 0){
            checkChildElementsFontsize(document, elements);
        }

        var count = 0;
      
        $.each(elements, function(index, value){
            if(!(value[0].attr('id')) || value[0].attr('id').indexOf("fontsize") != 0)
                value[0].css('font-size',(value[1]+(fontSizeInterval * fontSizeDiff))+'px');
        });

    });

    /*
    *    LANGUAGE-SWITCH
    */
    $("#header-ops-language-show-switch").click(function(){
        $("#header-ops-language-switch").toggle();
    });

    $("#header-ops-language-switch-select").change(function()
    {
        var newLanguage = $(this).val();

        var url = $("#language-switch-url").val().replace(/###LANG###/, newLanguage);

        location.href = url;
      
    });

    $(".box_tabs").tabs();
    
    $(".geoposition_description").hide();
    
    $(".geoposition_description_link").click(function()
    {
        if($(this).next().length > 0)
            if($(this).next().attr('class').indexOf("geoposition_description") > 0)
                $(this).next().toggle();
    });

    activateGalleryScroll();
    activateGalleryScrollVisual();
   
});

/*
 * Sicherheitscode
 */

var fieldGenerateSafetyCode;

function showLoginFailureDialog() {
    $("#dialog-widget-login-failure").dialog({
        modal:true,
        draggable:false,
        resizable:false,
        minWidth:600,
        open: function(e, ui) {
            projectTheme(this);
            var self = $(this);
            $("#load-dialog-forgot-password").unbind('click').click(function() {
                self.dialog('close');
                widgetForgotPassword();
            });
        }
    });
}

function getSafetyCode(field)
{
    fieldGenerateSafetyCode = field;
   
    $("#dialog-safetycode").dialog("open");

    var code = $("#safetycode_"+fieldGenerateSafetyCode).val();

    $("#dialog-safetycode").html(AjaxAPI('HelperAPI', 'generateSafetyCode', {
        safetyCode: code
    }));
}

function insertSafetyCode(code)
{
    $("#safetycode2_"+fieldGenerateSafetyCode).val(code);
    $("#dialog-safetycode").dialog("close");
}

function checkChildElementsFontsize(element, elements)
{
    $(element).children().each(function(index, element){
        var newFontSize = $(element).css('font-size').replace(/px/, '')*1;
        elements[elements.length] = new Array($(element), newFontSize);
        if($(element).children().length > 0)
            checkChildElementsFontsize(element, elements);
    });
}


function activateFAQ()
{
    $(".faq_link").click(function(){

        var id = $(this).attr('id').replace(/faqlink_/, '');

        $(".faq_answer").each(function(index, element)
        {
            if($(element).attr('id') != "faq_"+id && $(element).is(":visible"))
                $(element).hide('blind');

        });

        if($("#faq_"+id).is(":hidden"))
            $("#faq_"+id).show('blind');
        else
            $("#faq_"+id).hide('blind');

        return false;
    });
}

function activateEvents()
{
    $(".event_link").click(function(){

        var id = $(this).attr('id').replace(/eventlink_/, '');

        $(".event_text").each(function(index, element)
        {
            if($(element).attr('id') != "event_"+id && $(element).is(":visible"))
                $(element).hide('blind');

        });

        if($("#event_"+id).is(":hidden"))
        {
            if(!$("#event_"+id).hasClass("noSlide"))
                $("#event_"+id).show('blind');
        }
        else
            $("#event_"+id).hide('blind');

        return false;
    });
}

function checkBlur(element, value)
{
    if($(element).val() == '')
        $(element).val(value);
}

function checkFocus(element, value)
{
    if($(element).val() == value)
        $(element).val('');
}

function flyOutMenu()
{   
    $('.fg-flyout').each(function(i, menuLink) {
        menuLink = $(menuLink);
        menuLink.fgmenu({
            content: menuLink.next().html(),
            flyOut: true,
            callerOnState: '',
            flyOutOnState: '',
            linkHover: '',
            linkHoverSecondary: '',
            width: settings.flyOutMenuWidth,
            childLiTopPosition: settings.flyOutChildLiTopPosition,
            positionOpts: {
                posX: settings.flyOutMenuPosX,
                posY: 'bottom',
                offsetX: 0,
                offsetY: 0,
                directionH: 'right',
                directionV: 'down', 
                detectH: settings.flyOutMenuDetectH, // do horizontal collision detection  
                detectV: settings.flyOutMenuDetectV, // do vertical collision detection
                linkToFront: false,
                detectVSub: settings.detectVSub
            },
            showSpeed: settings.flyOutMenuShowSpeed
        //              loadingState: '',
        });
    });
    
    $('.fg-flyout-close').mouseover(function()
    {
        $.each(allUIMenus, function(i){
            if (allUIMenus[i].menuOpen) {
                allUIMenus[i].kill();
            };	
        });
    });
}

/*
 * REEL
 */

var state="hidden";
		var displayWidth,
			displayHeight,
			descriptionHeight,
			navigationHeight,
			padding,
			handleValue
		;

	function createImageStack(numberOfImages, prefix, imageExtension) {
		var strLenNumberOfImages = (numberOfImages + '').length;
		var imageStack = [];
		for (var i = 1; i <= numberOfImages; i++) {
			var name = i + '.' + imageExtension;
			while (name.length < (imageExtension.length + strLenNumberOfImages + 1)) {
				name = '0'+name;
			}
			name = prefix + name;
			imageStack.push(name);
		}
		return imageStack;
	}

	/* Get size of window or viewport */

	function getWindowSize() {
		if( typeof( window.innerWidth ) == 'number' ) {
		    //Non-IE
		    displayWidth = window.innerWidth;
		    displayHeight = window.innerHeight;
		} 
		else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		    //IE 6+ in 'standards compliant mode'
		    displayWidth = document.documentElement.clientWidth;
		    displayHeight = document.documentElement.clientHeight;
		} 
		else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		    //IE 4 compatible
		    displayWidth = document.body.clientWidth;
		    displayHeight = document.body.clientHeight;
		}
	}

	/* Resize image according to display */

	function resizeImage(imageID, imageWidth, imageHeight) {
		/*
                var strLenBorderWidth,
			strLenMargin,
			strLenPadding,
			strLenImageWidth,
			strLenImageHeight,
			strLenDescriptionPadding,
			descriptionPadding,
			borderWidth,
			margin,
			imageMargin,
			imageWidth,
			imageHeight,
			maxImageWidth,
			maxImageHeight,
			ratio,
			resizedImageWidth, 
			resizedImageHeight
		;
		getWindowSize();
		strLenDescriptionPadding = "10px".length;
		descriptionPadding = parseInt("10px".substring(0,strLenDescriptionPadding-1));
		strLenBorderWidth = "5px".length;
		strLenMargin = "5px".length;
		strLenPadding = "15px".length;
		strLenImageWidth = imageHeight+"px".length;
		strLenImageHeight = imageWidth+"px".length;
		borderWidth = parseInt("5px".substring(0,strLenBorderWidth-1));
		margin = parseInt("5px".substring(0,strLenMargin-1));
		padding = parseInt("15px".substring(0,strLenPadding-1));
		imageMargin = 2 * (borderWidth + margin + padding);
		imageWidth = parseInt(imageWidth+"px".substring(0,strLenImageWidth-1));
		imageHeight = parseInt(imageHeight+"px".substring(0,strLenImageHeight-1));
		maxImageWidth = Math.min(imageWidth,displayWidth - imageMargin);
		maxImageHeight = Math.min(imageHeight,displayHeight - imageMargin - descriptionHeight);
		if ((imageWidth / maxImageWidth) <= (imageHeight / maxImageHeight))
		  {
		  ratio = Math.floor((maxImageHeight / imageHeight)*100);
		  }
		else
		  {
		  ratio = Math.floor((maxImageWidth / imageWidth)*100);
		  }
		resizedImageWidth = Math.floor(imageWidth * ratio / 100);
		resizedImageHeight = Math.floor(imageHeight * ratio / 100);
		$("#"+imageID).attr('style', "width:" +resizedImageWidth + "px; height:" +resizedImageHeight + "px");
                */
               $("#"+imageID).attr('style', "width:" +imageWidth + "px; height:" +imageHeight + "px");
	}
        
        function projectTheme(el)
        {
            if($(el).parent().attr('class').indexOf("cms-project") != 0)
                $(el).parent().attr('class', "cms-project "+$(el).parent().attr('class'));
        }
        
        function getBaseURL() {
    var url = location.href;  // entire url including querystring - also: window.location.href;
    var baseURL = url.substring(0, url.indexOf('/', 14));

    if (baseURL.indexOf('http://localhost') != -1) {
        // Base Url for localhost
        var url = location.href;  // window.location.href;
        var pathname = location.pathname;  // window.location.pathname;
        var index1 = url.indexOf(pathname);
        var index2 = url.indexOf("/", index1 + 1);
        var baseLocalUrl = url.substr(0, index2);

        return baseLocalUrl + "/";
    }
    else {
        // Root Url for domain name
        return baseURL + "/";
    }
    
}

function gotoPage(url)
{
    if(url != "")
        window.location = url;
}

function initGeoposition(latitude, longitude, groups, zoom)
{
    if(typeof initGeopositionTheme == 'function')
        initGeopositionTheme(latitude, longitude, groups, zoom);
    else
        alert("Function does not exists");
}

function initShopProductFinder()
{
    if(typeof initShopProductFinderTheme == 'function')
        initShopProductFinderTheme();
    else
        alert("Function does not exists");
}
