﻿/* Modal window */
$.browser.msie6=$.browser.msie&&/MSIE 6\.0/i.test(window.navigator.userAgent)&&!/MSIE 7\.0/i.test(window.navigator.userAgent);$.fn.vCenter=function(a){var b={sTop:function(){return window.pageYOffset||$.boxModel&&document.documentElement.scrollTop||document.body.scrollTop},wHeight:function(){if($.browser.opera||$.browser.safari&&parseInt($.browser.version)>520){return window.innerHeight-($(document).height()>window.innerHeight?getScrollbarWidth():0)}else if($.browser.safari){return window.innerHeight}else{return $.boxModel&&document.documentElement.clientHeight||document.body.clientHeight}}};return this.each(function(a){if(a==0){var c=$(this);var d=c.outerHeight();c.css({position:"absolute",marginTop:"0",top:b.sTop()+b.wHeight()/2-d/2})}})};$.fn.modalWindow=function(a){var b=$.extend({},$.fn.modalWindow.defaults,a);var c=$("<div />").attr("class",b.classname),d=$("<div />").attr("class",b.contentClassname).appendTo(c),e=$("<div />").attr("class",b.contentClassname+"-inner clearfix").html(b.html).appendTo(d),f=$("<div />").attr("id","modal-shadow").css({height:$(document).height()+"px",opacity:"0.8"}).appendTo("body"),g=$("<a />").attr("class","modal-close").appendTo(c);if(/^(true)$/.test(b.customCorners)){var h=$("<div />").attr("class","btr"),i=$("<div />").attr("class","bbr"),j=$("<div />").attr("class","btl").appendTo(h),k=$("<div />").attr("class","bbl").appendTo(i);c.prepend(h).append(i).addClass("custom-corners")}c.css("width",b.contentWidth).prependTo("body");b.onOpen.call(c[0]);if(/^(true)$/.test(b.center)){var l=c.outerWidth();var m=c.outerHeight();c.css({position:"absolute",top:$(window).scrollTop()+$(window).height()/2+"px",left:"50%",marginLeft:"-"+(Math.ceil(l/2)-30)+"px",marginTop:"-"+Math.ceil(m/2)+"px"});if($.browser.msie6){c.vCenter();$(window).bind("scroll",function(){c.vCenter()})}}g.add(f).bind("click",function(){c.add(f).remove();b.onClose.call(c[0])});return c};$.fn.modalWindow.defaults={classname:"modal-window",contentClassname:"modal-content",contentWidth:"auto",center:true,customCorners:false,html:"",onOpen:function(){},onClose:function(){}}

/* Tooltip */
$.fn.tooltip=function(a){var b=$.extend({},$.fn.tooltip.defaults,a);return this.each(function(){function h(){d.remove()}function g(a){d.appendTo("body");f(a);d.css({opacity:0,display:"block"}).stop().animate({opacity:0},300,function(){d.animate({opacity:1},300)})}function f(a){var c=d.width();var e=d.height();b.Offset["x"]=-(c/2)-6;var f=$(document).width()-b.Offset["x"];var g=$(document).height()-b.Offset["y"];var h=a.pageX+b.Offset["x"];var i=a.pageY+b.Offset["y"]-e;d.css({top:i,left:h})}var a=$(this);var c=$(".artistcontent .col:first h3:first").text()+" på "+a.find("img").attr("alt");if(b.text!="element"){c=b.text}var d=$("<div />").attr("class",b.classname).text(c);var e=$("<span />").attr("class","arrow").appendTo(d);a.hover(g,h).mousemove(f)})};$.fn.tooltip.defaults={classname:"tooltip",text:"element",Offset:{x:0,y:-18}}

/* Slideshow */
var slideshowSpeed=7e3;
var photos=[
    {image:"img1.jpg",url:"assets/gfx/slideshow/img1.jpg"},
    {image:"img2.jpg",url:"assets/gfx/slideshow/img2.jpg"},
    {image:"img3.jpg",url:"assets/gfx/slideshow/img3.jpg"},
    {image:"img4.jpg",url:"assets/gfx/slideshow/img4.jpg"}
];

$(document).ready(function(){var a;$("#control").toggle(function(){h()},function(){$(this).css({"background-image":"url(assets/gfx/slideshow/btn_pause.png)"});e("next");a=setInterval(function(){e("next")},slideshowSpeed)});var b=1;var c=0;var d=false;var e=function(a){if(d){return}if(a=="next"){c++;if(c==photos.length+1){c=1}}else{c--;if(c==0){c=photos.length}}var e=b;if(b==1){b=2}else{b=1}g(photos[c-1],e,b)};var f=-1;var g=function(a,b,c){d=true;f--;$("#headerimg"+c).css({"background-image":"url(assets/gfx/slideshow/"+a.image+")",display:"block","z-index":f});$("#headerimg"+b).fadeOut(function(){setTimeout(function(){$("#headertxt").css({display:"block"});d=false},10)})};var h=function(){$("#control").css({"background-image":"url(assets/gfx/slideshow/btn_play.png)"});clearInterval(a)};e("next");a=setInterval(function(){e("next")},slideshowSpeed)})

/* Get first scrollable element $(html, body) */
var getScrollable=function a(a){var b=[],c=false,d=a.dir&&a.dir==="left"?"scrollLeft":"scrollTop";this.each(function(){if(this===document||this===window){return}var a=$(this);if(a[d]()>0){b.push(this);return}a[d](1);c=a[d]()>0;a[d](0);if(c){b.push(this);return}});if(a.el==="first"&&b.length){b=[b.shift()]}return b};$.fn.extend({firstScrollable:function(a){var b=getScrollable.call(this,{el:"first",dir:a});return this.pushStack(b)}})


/* #NAVIGATION
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
function navAnimation() {   
    
    var hash = window.location.hash, 
        newHash, $currDiv, $link;

    // If the url already has a hash
    if(hash.length > 0)
    {   
        // If the hash has a "/". Load the right content-page
        if(hash.indexOf("/") > -1)
        {
            newHash = hash.split("/");
            
            if($('body').find(newHash[0]).length > 0)
            {
                $currDiv = $('body').find(newHash[0]),
                $link = $(newHash[0]);
                
                $currDiv.find('.sub-nav .active').removeClass('active');
                $currDiv.find('.sub-nav a').each(function()
                {
                    if($(this).attr('href').indexOf(newHash[1]) > -1)
                    {
                        var $ajaxcontainer = $currDiv.find('.ajaxcontent'),
                            link = newHash[0].substr(1) + "/" + newHash[1];
                        
                        $(this).parent().addClass('active');
                        $ajaxcontainer.load(link + " .ajaxcontent div", function(){
                            $('.table-wrap tbody tr:even').addClass('even');
                        });
                    }
                });
                
                $('html, body').animate({'scrollTop' : $link.offset().top + 'px' });
            }
        }
        else if (hash.indexOf("home") > -1) {
            $('html, body').animate({'scrollTop' : '99999px' });   
        }
        else {
            $link = $(hash);
            $('html, body').animate({'scrollTop' : $link.offset().top + 'px' });
        }
    }
    
    // if no hash exists. Do this after page has loaded to make sure we end up in the bottom of the document when going to "#home" the first time
    else {
        window.location.hash = '#home';
        $('html, body').animate({'scrollTop' : '99999px' });
    }
    
}


/* ARTIST POPUP
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
function popupArtist(artistUrl) {
    $.fn.modalWindow(
    {
        html: '',
        contentWidth: '840px',
        classname: 'modal-window pop-artist',
        onOpen: function() {
            $(this).find('.modal-content-inner').load(artistUrl + "?v=10" + " .artistcontent", function() {
                if ( !$.browser.msie ) {
                    $('.social-links a').tooltip();
                }
            });
        }
    });
}

/* NEWS POPUP
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
function popupNews(artistUrl) {
  $('.pop-news').add('#modal-shadow').remove();
    $.fn.modalWindow(
    {
        html: '',
        contentWidth: '510px',
        classname: 'modal-window pop-news',
        onOpen: function() {
            $(this).find('.modal-content-inner').load(artistUrl + "?v=10" + " .artistcontent");
        }
    });
}


/* #News Slider
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
function newsSlider () {
    var $this = $('#news-slider');
        
    if($this.children().length > 1) {
    
      var timer = null;
      
      function slideUp() {
        $this.children(':first').stop(true,false).animate({'opacity':'0'}, 500, function() {
          $this.animate({'top' : '-' + $this.children(':first').outerHeight(true)}, 500, function() {
            // Return the "left" CSS back to 0, and append the first child to the very end of the list.
            $this
               .css('top', 0)
               .children(':first')
               .css('opacity','1')
               .appendTo($this); // move it to the end of the line.
          })
        });
      }
      
      function stop() {
        clearTimeout(timer);
      }
      
      function startTimer() {
        timer = setTimeout(function() {
          slideUp();
          startTimer();
        }, 6000);
      }
      startTimer();
      
    }
}


/* #DOM-READY
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
jQuery(function() {


    newsSlider();

    // Load initial content
    $('#program .ajaxcontent').load("program/artister.html .ajaxcontent div");

    // Page navigation
    navAnimation();
    
    // Handle clicks on main-menu links
    $('.primary-nav a, #bottom-nav a').bind('click', function(e) {
        var $this = $(this),
            $link = $($this.attr('href')),
            animationTime = Math.abs($(this).offset().top - $link.offset().top) / 2;
        
        e.preventDefault();
        
        $('html, body').firstScrollable().animate({'scrollTop' : $link.offset().top}, animationTime, function() {
            window.location.hash = $link.attr('id');
            /* if ($link.selector === '#priser')...*/
        });
    });

    
    // Handle clicks on sub-menu links
    $('.sub-nav').find('a').bind('click',function(e) {

        var $this = $(this),
            link = $this.attr('href'),
            $ajaxcontainer = $this.parents('.wrap').find('.ajaxcontent');

        e.preventDefault();

        // Prevent clicks on already active page
        if ($this.parent().is('.active')) {
            return false;
        }
            
        //$('#program .ajaxcontent').removeClass('initial-content');
            
        $this.parents('.wrap').find('.sub-nav li.active').removeClass('active');
        $this.parents('li').addClass('active');
        
        if(!$.browser.msie)
        {
            $ajaxcontainer.stop().animate({opacity:0}, 200, function(){
                $ajaxcontainer.load(link + " .ajaxcontent div", function(){
                    $('.table-wrap tbody tr:even').addClass('even');
                    var newHash = link.split("/");
                    window.location.hash = newHash[0] + "/" + newHash[1];
                    $ajaxcontainer.stop().animate({opacity:1}, 200);
                    
                });
            });
        }
        else{
            $ajaxcontainer.load(link + " .ajaxcontent div", function(){
                $('.table-wrap tbody tr:even').addClass('even');
                var newHash = link.split("/");
                window.location.hash = newHash[0] + "/" + newHash[1];
            });
        }
    });
    
    $('#quicklink-restaurant').bind('click', function (e) {
        window.location.hash = "#program/restaurangtalt.html";
        navAnimation();
        e.preventDefault();
    });
    
    $('#more-history').bind('click',function(e) {
        
        var html_string = "<h3>Några av de artister som gästat Stadsfesten</h3><ul class=\"artists\"><li>Europe</li><li>Robyn</li><li>Tomas Ledin</li><li>Soundtrack of our Lives</li><li>Lena & Orup</li><li>Ace Of Base</li><li>Sahara Hotnights</li><li>Salem</li><li>The Ark</li><li>Lasse Berghagen</li><li>Christian Walz</li><li>Erik Hassle</li><li>Andreas Johnson</li><li>Carola</li><li>E-Type</li><li>Petter</li><li>Jill Johnson</li><li>BWO</li><li>Teddybears</li><li>Electric Banana Band</li><li>Martin Stenmarck</li><li>Calaisa</li><li>Melody Club</li><li>Lisa Miskovsky</li><li>Blowsight</li><li>Markoolio</li><li>EMD</li><li>Kleerup</li><li>Amy Diamond</li><li>Tomas Andersson Wij</li><li>Amanda Jenssen</li><li>Florence Valentin</li><li>Lillasyster</li><li>Bullet</li><li>Kevin Borg</li><li>Johan Palm</li><li>Lorentz & M. Sakarias</li><li>Kristian Anttila</li><li>Darin</li><li>mfl. mfl</li></ul>";
        $.fn.modalWindow(
        {
            html: html_string,
            contentWidth: '600px',
            classname: 'modal-window pop-history'
        });
        e.preventDefault();
        
    });
    
    $('.pop-signup').live('click', function(e){
        var link = $(this).attr('href');
        $.fn.modalWindow(
        {
            html: '',
            contentWidth: '840px',
            classname: 'modal-window pop-submitform',
            onOpen: function() {
                $(this).find('.modal-content-inner').load(link + " #signup-form");
            }
        });
        return false;
    });
    
    $('body').delegate('#signup-form', 'submit', function() {
        var values = $(this).serialize();
        var errorMessage = '<p class="validation-error">Vi måste få veta antingen din <label for="epost">e-post</label> eller ditt <label for="telefon">telefonnummer</label> för att kunna bekräfta beställningen</p>';
        
        if( $('#epost').val() == "" && $('#telefon').val() == "" ) {
            $('#signup-form').append(errorMessage);
        }
        else {
            $(this).html('<div id="loading"><img src="/assets/gfx/loading.gif" width="32" height="32" alt="" /><span>Skickar beställning...</span></div>');
            $.post("/priser/ajaxsubmit.php", values, function(data){
                var message = '<p class="status">' + data + '</p>';
                $('#signup-form').html(message);
            });
        }
        
        return false;
    });
    
    $('body').delegate('#register-form', 'submit', function() {
        var values = $(this).serialize();
        var errorMessage = '<p class="validation-error">Vi måste få veta <label for="deltagare">deltagare</label>, <label for="alder">ålder</label> och antingen din <label for="epost">e-post</label> eller ditt <label for="telefon">telefonnummer</label> för att kunna bekräfta din anmälan</p>';
        
        if( ( $('#deltagare').val() == "" || $('#alder').val() == "" ) || ( $('#epost').val() == "" && $('#telefon').val() == "" ) ) {
            $('#register-form').append(errorMessage);
        }
        else {
            $(this).html('<div id="loading"><img src="/assets/gfx/loading.gif" width="32" height="32" alt="" /><span>Skickar anmälan...</span></div>');
            $.post("/program/smastjarnorna/ajaxanmalan.php", values, function(data){
                var message = '<p class="status">' + data + '</p>';
                $('#register-form').html(message);
            });
        }
        
        return false;
    });
    
    
    $('.artist-links a, .old-artist-links a', $('#program')[0]).live('click',function(e){
        var link = $(this).attr('href');
        popupArtist(link);
        e.preventDefault();
    });
    
    $('.table-wrap a', $('#program')[0]).live('click',function(e){
    
        if ($(this).hasClass('no-popup')) {
            return true;
        }
    
        var link = $(this).attr('href');
        if(! $(this).hasClass('nopop') ) {
            popupArtist(link);
            e.preventDefault();
        }
    });
    
    $('#more-news').live('click',function(e){
        var link = $(this).attr('href');
        popupNews(link);
        e.preventDefault();
    });
  
    $('#bottom-nav li:first-child a').bind('click',function(e){
        var link = 'nyheter/archive.php';
        popupNews(link);
        e.preventDefault();
    });
  
    $('#news-slider a').bind('click',function(e){
        var link = $(this).attr('href');
        popupNews(link);
        e.preventDefault();
    });
  
  $('.news-archive a').live('click', function(e) {
        var link = $(this).attr('href');
        popupNews(link);
        e.preventDefault();
  });
    
});
