﻿/* Author: Dan Kjær Jessen */
var CMS = CMS || {}; 
    CMS.modules = CMS.modules || {};

/**	
 * jQuery pub/sub plugin by Peter Higgins (dante@dojotoolkit.org)
 * Loosely based on Dojo publish/subscribe API, limited in scope. Rewritten blindly.
 * Original is (c) Dojo Foundation 2004-2010. Released under either AFL or new BSD, see:
 * http://dojofoundation.org/license for more information.
 *
 *  @link https://github.com/phiggins42/bloody-jquery-plugins/blob/master/pubsub.js
 */	

;(function(d){
	var cache = {};

	d.publish = function(/* String */topic, /* Array? */args){
		cache[topic] && d.each(cache[topic], function(){
			this.apply(d, args || []);
		});
	};

	d.subscribe = function(/* String */topic, /* Function */callback){
		if(!cache[topic]){
			cache[topic] = [];
		}
		cache[topic].push(callback);
		return [topic, callback]; // Array
	};

	d.unsubscribe = function(/* Array */handle){
		var t = handle[0];
		cache[t] && d.each(cache[t], function(idx){
			if(this == handle[1]){
				cache[t].splice(idx, 1);
			}
		});
	};

})(window.jQuery);


/* Console.log wrap */
window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console) {
      arguments.callee = arguments.callee.caller;
      console.log( Array.prototype.slice.call(arguments) );
  }
};
// make it safe to use console.log always
(function(b){function c(){}for(var d="assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,time,timeEnd,trace,warn".split(","),a;a=d.pop();)b[a]=b[a]||c})(window.console=window.console||{});


 /**
 * Et modul, der sørger for, at starter en billed- fader/cycler.
 * funktionaliteten har knapper, så det er muligt at bladre mellem
 * billederne
 *  
 * @module fotofade
 * @namespace CMS
 * @param   {Object}              $   jQuery object
 * @return  {Object}              {}  returns the public functions
 */
CMS.fotofade = (function($){

    var idx,
        $id,
        $resume,
        $pause,
        $nav_a,
        $wrap,

        applyCycle = function(id) {
            console.log("-- applying jquery cycle to id: "+id);
            
            // define cycle
            $id.cycle({
                allowPagerClickBubble: true,
                after: handleTransition,
                onPagerEvent: handlePauseClick,
                startingSlide: 0, 
                fx: 'fade', 
                speed: 'fast', 
                pager: "#fotofade_wrap .nav", 
                timeout: 3000
                }
            );          

            $("#fotofade_wrap .ff_text:eq(0)").css({"top":"241px"});
            setupHandlers();
        },

        setupVars = function(id) {
            $id = $(id);
            $wrap = $("#fotofade_wrap");
            $nav_a = $wrap.find(".nav a");
            $resume = $wrap.find(".navResume");
            $pause = $wrap.find(".navPause");
        },

        setupHandlers = function() {
            $resume.hide();
            $pause.click(handlePauseClick);
            $resume.click(handleResumeClick);
        },

        handleTransition = function(currSlideElement, nextSlideElement, options, forwardFlag) {
            idx = $(".ff_img").index(nextSlideElement);
            var $elem = $("#fotofade_wrap .ff_text:eq("+idx+")"),
                position = 275 - ($elem.outerHeight() - 41);

            $elem.css({"top":position+"px"});

            idx = $(".ff_img").index(currSlideElement);
            $("#fotofade_wrap .ff_text:eq("+idx+")").css({"top":"-99999px"});
        },

        handleResumeClick = function() {
            console.log("aviva cms: fotofade resume event.");
            $resume.hide();
            $pause.show();
            $id.cycle('resume');
            return false;
        },

        handlePauseClick = function() {
            console.log("aviva cms: fotofade pause event.");
            $resume.show();
            $pause.hide();
            $id.cycle('pause');
            return false;
        },
        
        init = function(id) {
            setupVars(id);
            // check if cycle plugin is loaded
            if(typeof $.fn.cycle !== 'function') {
                console.log("aviva cms: no cycle library");
                console.log("-- loading jquery.cycle.all.js");
                $.getScript('scripts/jquery.cycle.all.js', applyCycle(id));
            } else {
                applyCycle(id);
            }            
        };

    // hook up on init event
    $.subscribe("/cms/fotofade/init", function(params) {
        console.log("aviva cms: running fotofade module:");
        init(params);
    });

}(window.jQuery));



 /**
 *  A module to handle the menu
 *    
 * 
 * @module menu
 * @namespace CMS
 * @param   {Object}              $   jQuery object
 * @return  {Object}              {}  returns the public functions
 */
CMS.menu = (function($){

    var $id,
        $elem,
        lookup = {},
        mouseIsOver = false,

        leftPos = $("#container").offset().left + 10,
        leftElem,

        setupHandlers = function () {
            $("#xm_2").find("li.xm_0").each(
                function(idx,elem) {
                    $elem = $(elem);
                    $elem
                        .bind('mouseover',menuOver)
                        .bind('mouseout', menuOut);

                    $id = $elem.attr('id');
                    lookup[$id] = $('#hover_menu' + $id.substring(3));
                    lookup[$id].bind('mouseout', submenuOut)
                               .bind('mouseover', submenuOver);
                }
            );
        },

        menuOver = function(e) {
            lookup[$(this).attr('id')].show();
        },
        
        menuOut = function(e) {
            var $thisId = $(this).attr('id');
            window.setTimeout(
                function() {
                    if(!mouseIsOver) { lookup[$thisId].hide(); }
                }, 
            800);
        },

        submenuOut = function(e) {
            $(this).hide();
            mouseIsOver = false;
        },

        submenuOver = function(e) {
            mouseIsOver = true;
        },

        init = function() {
            $(".hover_menu").each(
                function(idx,elem) {
                    $elem = $(elem);
                    $('#xmi'+$elem.attr('id').substring(10)).append($elem);
                    leftElem = leftPos - $elem.offset().left;
                    $elem.css({"left": leftElem+"px", "top": "35px;" });
                }
            );
           //setupHandlers();
        };

    /* startup the module */
    init();
    
}(window.jQuery));

 /**
 * LightBox LSS Aviva CMS modul
 *
 * @module lightBox
 * @namespace CMS
 * @param   {Object}              $   jQuery object
 * @return  {Object}              {}  returns the public functions
 */
CMS.lightBox = (function($){ 
    var params, 

        applyLightBox = function() {
            $.each(
                params, 
                function(index,value){
                    console.log("-- applying jquery lightbox to id: " + value);
                    $(value).lightBox();
                }
            );
        },

        init = function(inparams) {
            params = inparams;
            // check if lightbox plugin is loaded
            if(typeof $.fn.lightBox !== 'function') {
                console.log("aviva cms: no lightbox library");
                console.log("-- loading jquery.lightbox-0.5.min.js");
             $.getScript('scripts/jquery.lightbox-0.5.min.js', applyLightBox);
            } else {
                applyLightBox();
            }
        };

    // hook up on init event
    $.subscribe("/cms/lightBox/init", function(params) {
        console.log("aviva cms: running lightbox module:");
        init(params);
    });
}(window.jQuery));

/**
 * Et modul, der ansvarlig for, at starte andre moduler op, så
 * funktionalitet kommer ind på siden
 *  
 * @module init
 * @namespace CMS
 * @param   {Object}              $   jQuery object
 * @return  {Object}              {}  returns the public functions
 */

CMS = CMS || {};
CMS.init = (function($){
    var init = function() {
        // check if any modules are needed
        if(!CMS.modules) return

        // loop all modules and start them
        $.each(
            CMS.modules,
            function(key,value) {
                if(typeof value === 'function') { 
                    value(); 
                } else {
                    $.publish("/cms/"+key+"/init", [value]);
                }
            }
        );
    };

    ///////////////////////////////////////////////////////////
    // run the modules
    init();
})(window.jQuery);




