/*
*	Method to overwrite the src in a mutlisize image to change
*	the picture displayed before zoom with the alternative picture
*	in_article_image
*/

var DifferentZoomPicture = new Class({
   changeZoomFrontPicture: function (){
       var picturesToChange = $$('.different_frontpicture');
       for(var i = 0; i < picturesToChange.length; i++){
	   var oldSrc = picturesToChange[i].get('image_url');
	   var srcSplit = oldSrc.split('the_image');
	   srcSplit[0] += 'in_article_image';
	   picturesToChange[i].set('src',srcSplit[0]);
       }
   }
})

/*
*	Changes the hash to empty, this method is called
*	when the back button is used from articles or galleries.
*	This enables the history to work correctly.
*/



var StartPageUrl = new Class({
    changeUrl: function(){
	document.title = $('firstPageTitle').get('name');
        window.location.hash = '';
	$('pvms_history_check_id').store('history','');
    }
})


/*
 *	Used for the redirect in the page, replaces the ? with a #
 *	to remove page reload
 */

if (window.location.search){
        var l = window.location;
        window.location.replace(l.protocol + "//" + l.host + l.pathname + l.search.replace("?", "#").replace('%21','!'));
}


/*
 *	Function polling the hash in the address bar to detect changes 
 *	which triggers a relocation to the correct page. It is polling
 *	once per sec.
 *
 *	If going back from a stickywin-instance, it and any mask used
 *	will be changed to display:none
 *
 */
function checkHash(){
    var prevHash = $('pvms_history_check_id').retrieve('history','');
    if((window.location.hash=='')){
        if(window.location.hash != prevHash){
            $('pvms_history_check_id').store('history','');
            $('modal_container').setStyle('display','none');
	    var maskList = $$(".mask");
	    for(var i = 0; i < maskList.length; i++){
		if(!maskList[i].hasClass('iscroll_viewport')){
		    maskList[i].setStyle('display','none');
		}
	    }
	    var stickyWins = $$(".StickyWinInstance");
	    if (stickyWins.length != 0){                         
		stickyWins[0].setStyle('display','none');
	    }
        }
    }
    if((window.location.hash != prevHash)){
        $('pvms_history_check_id').store('history',window.location.hash);
        var url = window.location.href;
                url = url.replace("#!","/navigateJson?!");
                json_action_request(url, {}, undefined, 'get');
    }
}

function checkFlash(){
    if (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]){
	//parse out parameters from html5 video tag and inject flowplayer
    }
}

function refreshIScroll() {
    var elements = $$('.iscroll_content');
    if(elements.length!=0){
        Array.each(elements, function(element){
            if (element.retrieve('iscroll')){
                element.retrieve('iscroll').refresh();
            }
        });
    }
}

window.refreshAllIscrolls = function(){
    var elements = $$('.iscroll_content');
    if(elements.length!=0){
        Array.each(elements, function(element){
            if (element.retrieve('iscroll')){
                element.retrieve('iscroll').refresh();
            }
        });
    }
}


window.addEvent('domready',function(){
        window.addEvent('resize', function(){
                var child = $$(".DefaultPointyTip.menu");
                if (child.length != 0){                         
                        var itemToRemove = child[0].getParent();
                        itemToRemove.setStyle('display','none');
                }
        });
        checkFlash();
        checkHash();
        checkHash.periodical(1000);
        var menu_button = $('menu_button');
        menu_button.setStyle('height','100px');
        menu_button.addEvent('click', function(event){
                var popup_menu_content;
                
                event.stop();
                
                popup_menu_content = $$('.menu_container')[0].clone();
                
                if (is_ipad){
                    menu_with = 380
                }
                else{
                     menu_with = 397
                }
                
                var pointy = new StickyWin.PointyTip('News', popup_menu_content, {
                    point           : 11,
                    relativeTo      : 'menu_button',
                    offset          : {x: -121, y: -19},
                    allowMultiple   : false,
                    closeOnEsc      : true,
                    closeOnClickOut : true,
                    destroyOnClose  : true,
                    closeClassName  : 'menu_content',
                    pointyOptions   : {
                        theme: 'menu',
                        themes: {
                            menu: {
                                cssClass: "menu",
                                css: 'se style.css samt ipad.css',
                                divotSize: 35,
                                width: menu_with, //397 om desktop, 380 om ipad
                                closeButton: false
                            }
                        }
                    }
                });
                
                activate_elements(popup_menu_content);
                pageTracker._trackEvent("user", "innehållPressed", "");
                
        }.bind(this));
        $('pvms_history_check_id').store('StartPageUrl',new StartPageUrl());
	$('pvms_history_check_id').store('changePic',new DifferentZoomPicture());

        //(function () {
                refreshIScroll();
        //}).delay(500);
});

window.share_menu = function(share_menu_content){
    var share_button = $('share_button');
    if (is_ipad){
        menu_with = 380
    }
    else{
         menu_with = 397
    }
    
    new StickyWin.PointyTip('Share', share_menu_content, {
        point           : 11,
        relativeTo      : 'share_button',
        offset          : {x: -menu_with + 80, y: -19},
        allowMultiple   : false,
        closeOnEsc      : true,
        closeOnClickOut : true,
        destroyOnClose  : true,
        closeClassName  : 'menu_content',
        pointyOptions   : {
            theme: 'menu',
            themes: {
                menu: {
                    cssClass: "menu share",
                    css: 'se style.css samt ipad.css',
                    divotSize: 35,
                    width: menu_with, //397 om desktop, 380 om ipad
                    closeButton: false
                }
            }
        }
    });
}
// Dödar alla StickyWinInstances
window.destroy_all_StickyWinInstance = function(){
    $$('div.StickyWinInstance').each(function(sw) {
        sw.retrieve('StickyWin').destroy();
    });
}

// slide show
function setupSlideShow(element) {
    if (element.getElements('#big_promo_carousel').length > 0) {
        var random_slide_interval = Math.floor(Math.random()*1000) + 6000;
        new SimpleCarouselUrbantalk(element.getElements('#big_promo_carousel')[0], $$('#big_promo_carousel div.big_promo_container'), null, {
            rotateActionDuration: 1000,
            transitionDuration: 150,
            slideInterval: random_slide_interval,
            autoplay: true,
            hasPrevNextButtons: true,
            navigationContainer: '#big_promo_carousel_navigation',
            prevButton: '#big_promo_carousel_navigation .navigate_left',
            nextButton: '#big_promo_carousel_navigation .navigate_right',
            currentSlideIndexElement: '#big_promo_carousel_navigation .current_slide_index',
            numberOfSlidesElement: '#big_promo_carousel_navigation .number_of_slides'
        });
    }
    
    if (element.getElements('#distributor_search_1_carousel').length > 0) {
        var random_slide_interval = Math.floor(Math.random()*1000) + 4000;
        new SimpleCarouselUrbantalk(element.getElements('#distributor_search_1_carousel')[0], $$('#distributor_search_1_carousel div.small_promo_content_container'), null, {
            rotateActionDuration: 500,
            transitionDuration: 150,
            slideInterval: random_slide_interval,
            autoplay: true,
            hasPrevNextButtons: true,
            navigationContainer: '#distributor_search_1_carousel .navigation',
            prevButton: '#distributor_search_1_carousel .navigation .navigate_left',
            nextButton: '#distributor_search_1_carousel .navigation .navigate_right',
            currentSlideIndexElement: '#distributor_search_1_carousel .navigation .current_slide_index',
            numberOfSlidesElement: '#distributor_search_1_carousel .navigation .number_of_slides'
        });
    }
    
    if (element.getElements('#distributor_search_2_carousel').length > 0) {
        var random_slide_interval = Math.floor(Math.random()*1000) + 4000;
        new SimpleCarouselUrbantalk(element.getElements('#distributor_search_2_carousel')[0], $$('#distributor_search_2_carousel div.small_promo_content_container'), null, {
            rotateActionDuration: 500,
            transitionDuration: 150,
            slideInterval: random_slide_interval,
            autoplay: true,
            hasPrevNextButtons: true,
            navigationContainer: '#distributor_search_2_carousel .navigation',
            prevButton: '#distributor_search_2_carousel .navigation .navigate_left',
            nextButton: '#distributor_search_2_carousel .navigation .navigate_right',
            currentSlideIndexElement: '#distributor_search_2_carousel .navigation .current_slide_index',
            numberOfSlidesElement: '#distributor_search_2_carousel .navigation .number_of_slides'
        });
    }
    
    if (element.getElements('#follow_us_carousel').length > 0) {
        var random_slide_interval = Math.floor(Math.random()*1000) + 3000;
        new SimpleCarouselUrbantalk(element.getElements('#follow_us_carousel')[0], $$('#follow_us_carousel p'), null, {
            rotateActionDuration: 1000,
            transitionDuration: 500,
            slideInterval: random_slide_interval,
            autoplay: true,
            hasPrevNextButtons: false
        });
    }
}
window.element_activators.push(setupSlideShow); // See json-action-links.js for more on element activators

// Pageflip
(function($,$$) { window.addEvent('domready',function() {
    if ($('page-flip')){
        var flip = $('page-flip');
        var flipImage = $('page-flip-image');
        var flipMessage = $('page-flip-message');
        var speed;
        this.flipIsOpen = false;
        
        flip.addEvents({
            mouseenter:function() {
                openFlip();
                pageTracker._trackEvent('page_flip', 'revealed')
            },
            mouseleave:function() {
                closeFlip();
            }  
        });
        
        function openFlip(speed){
            this.flipIsOpen = true;
            if (!speed){
                speed = 500;
            }
            
            $$(flipImage,flipMessage).set('morph',{ duration: speed }).morph({
                width: 307,
                height: 319
            });
        }
        
        function closeFlip(){
            this.flipIsOpen = false;
            flipImage.set('morph',{ duration: 220 }).morph({
                width: 50,
                height: 52
            });
            flipMessage.set('morph',{ duration:200 }).morph({
                width: 50,
                height:50
            });
        }
        
        function autoflip(){
            if(this.flipIsOpen === false){
                (function () {
                    openFlip(8000);
                    this.flipIsOpen = false;
                }.bind(this)).delay(500);
                
                (function () {
                    if(this.flipIsOpen === false){
                        closeFlip();
                    }   
                }.bind(this)).delay(1200);
                
                
            }
            
            (function () {
                autoflip();
            }.bind(this)).delay(5000);    
        }
        autoflip();
    }
}); })(document.id,$$);


/*

        THIS IS TUX; I AM YOUR MASTER; FLYTTAT FRÅN URBANTALK UTIL    

*/


var setShareUrl = function(){
    var object_name = '';
    var old_url;
    var new_url;
    
    if($$('.slidetrack_thumbbar .thumbnail_container.current .slidetrack_thumbnail')[0]){
        object_name = $$('.slidetrack_thumbbar .thumbnail_container.current .slidetrack_thumbnail')[0].getProperty('object_name');
    }
    else if($$('.article_width_container')[0]){
        object_name = $$('.article_width_container')[0].getProperty('object_name');
    }
    
    
    if(object_name){
        if($$('.article_menu_container #share_button a')[0]){
            old_url = $$('.article_menu_container #share_button a')[0].getProperty('href');
            new_url = new URI(old_url);
            new_url.set('query', 'object_name=' + object_name);
            $$('.article_menu_container #share_button a')[0].setProperty('href', new_url.toString())
        }
    }
}


//needs clientcide
var SimpleCarouselUrbantalk = new Class({
    Extends: SimpleCarousel,
    
    options: {
        hasPrevNextButtons: false,
        prevButton: '#prev',
        nextButton: '#next'
	},
	initialize: function(container, slides, buttons, options){
	    this.parent(container, slides, buttons, options);
	    
	    // stop autoplay if there is only one slide
	    if(this.slides !== undefined && this.slides.length < 2){
	        this.stop();
	    }
	    
	    if(this.options.hasPrevNextButtons === true){
	        this.setupPrevNextButtons(0);
	        
	        //set total numbers
	        $$(this.options.numberOfSlidesElement)[0].set('text', this.slides.length);
	    }
	},
	showSlide: function(slideIndex){
	    this.parent(slideIndex);
	    
	    if(this.options.hasPrevNextButtons === true){
	        this.setupPrevNextButtons(slideIndex);
        }
	},
	setupPrevNextButtons: function(currentIndex){
	    var self = this;
	    var numberOfSlides = this.slides.length;
	    var numberOFSlidesIndex = numberOfSlides - 1;
	    var prevIndex;
	    var nextIndex;
        
	    //show contorls
	    if(numberOfSlides > 1){
	        $$(this.options.prevButton)[0].removeEvents('click');
	        $$(this.options.nextButton)[0].removeEvents('click');
	        
	        //prev button setup
	        if(currentIndex <= 0){
                prevIndex = numberOFSlidesIndex;
	        }
	        else{
	            prevIndex = currentIndex - 1;
	        }
	        $$(this.options.prevButton)[0].addEvent('click', function(){
                self.showSlide(prevIndex);
                currentIndex = prevIndex;
                self.setupPrevNextButtons(currentIndex);
                self.stop();
                return false;
            });
            
            //next button setup
            if(currentIndex >= numberOFSlidesIndex){
                nextIndex = 0;
	        }
	        else{
	            nextIndex = currentIndex + 1;
	        }
            $$(this.options.nextButton)[0].addEvent('click', function(){
                self.showSlide(nextIndex);
                currentIndex = nextIndex;
                self.setupPrevNextButtons(currentIndex);
                self.stop();
                return false;
            });
            
            //set current number
            $$(this.options.currentSlideIndexElement)[0].set('text', currentIndex + 1);
	    }
	    //hide controls
	    else{
	        $$(this.options.navigationContainer)[0].setStyle('display', 'none');
	    } 
	}
});
