$(document).ready(function(){
	
	if($.query.get('unlock') == 'bombayworks'){
		setCookie("sjMelodifestivalenUnlocked", "true", 2020, 01, 01, '/');
	}
	
	if(!getCookie("sjMelodifestivalenUnlocked")){
		
		$('body').append('<div id="overlayBox"><div id="overlay"></div><div id="overlayContent">'
						 +'<h1>Kampanjen är slut för den här gången.</h1><p>Tack alla som deltog. Hälsningar <a href="http://www.sj.se/">SJ</a></p>'
						 +'</div></div>');
		
		$('#overlay').css('height',$(document).height()+'px');
		$('#overlay').css('width',$(document).width()+'px');
		$('#overlay').fadeTo(0,0);
		$('#overlay').fadeTo(1500,0.7);
		$('#overlayContent').fadeTo(0,0);
		$('#overlayContent').fadeTo(2000,1);
		
		$('#overlayContent').animate({marginTop:($(document).scrollTop() + 120)+'px'},1000);
		$(document).scroll(function(){
			$('#overlayContent').stop();
			$('#overlayContent').animate({marginTop:($(document).scrollTop() + 120)+'px'},1000);
		});
	}
});


jQuery.fn.browseArtist = function(){

	if($(this).length != 1){
		return;
	}
	var button_layer = $(this).find('.text-and-buttons');
	var next = $(this).find('.text-and-buttons .next');
	var prev = $(this).find('.text-and-buttons .prev');
	
	var text = $(this).find('.text-and-buttons .text');
	var link = $(this).find('.text-and-buttons .read-more');
	
	var slides = $(this).find('.picture-layer ul');
	var interval;
	var locked = false;
	
	function init(){
			//move slides so that the active slide is the first one
			var b = false;
			slides.find('li').each(function(i, s){
				if($(s).hasClass('active'))
					b = true;
				
				if(b == false){
					slides.append($(s));	
					$(s).css('margin-left','0px');
				}
				
				$(s).click(function(){
					window.location.href = $(this).metadata().url;
				});
			});
			
			$(this).find('.interface-frame img').click(function(){
				window.location.href = slides.find('li:first').metadata().url;
			});
			//bind buttons
			next.click(function(){
				//resetInterval();
				next_slide(); 
				return false;
			});
			prev.click(function(){
				//resetInterval();
				prev_slide(); 
				return false;
			});
			showInfo();
			
			//resetInterval();
	}
	
	function resetInterval(){
		if(interval)
			clearInterval(interval);
		
		interval = setInterval(next_slide,8000);
	}
	
	
	function next_slide(){
		if(locked)
			return;
		
		hideInfo();	
		slides.find('li:first').animate({marginLeft:'-'+slides.find('li:first').width() +'px'},800,"swing", function(){
			slides.append(slides.find('li:first'));	
			slides.find('li:last').css('margin-left','0px');
			showInfo();
		});			
	}
	
	function prev_slide(){
		if(locked)
			return;
		
		hideInfo();	
		slides.find('li:last').css('margin-left','-'+slides.find('li:last').width() +'px');
		slides.prepend(slides.find('li:last'));
		
		slides.find('li:first').animate({marginLeft:'0px'},800,"swing", function(){
			showInfo();		
		});
		
	}
	
	function hideInfo(){
		text.fadeOut('slow');
		link.fadeOut('slow');
		locked = true;	
	}
	
	function showInfo(){
		text.html('<span class="green">Artist:</span> <a href="'+slides.find('li:first').metadata().url+'">'+slides.find('li:first').metadata().text+'</a>');
		link.attr('href',slides.find('li:first').metadata().url);
		text.fadeIn('slow');
		link.fadeIn('slow');
		locked = false;
	}
	
	init();

};

jQuery.fn.slideshow = function(){

	if($(this).length != 1){
		return;
	}
	var button_layer = $(this).find('.text-and-buttons');
	var next = $(this).find('.text-and-buttons .next');
	var prev = $(this).find('.text-and-buttons .prev');
	var pages = $(this).find('.pages');
	
	var slides = $(this).find('.picture-layer ul');
	var interval;
	var locked = false;
	var jump = 0;
	
	function init(){
			//fix page numbers
			var count = 0;
			slides.find('li').each(function(){
				++count;
				$(this).metadata().page = count;
				pages.append('<a class="page_'+count+' {page:'+count+'}" href="#">'+count+'</a>');
				
				$(this).click(function(){
					window.location.href = $(this).metadata().url;
				});
			});
			pages.find('a').click(function(){
				move_to_slide($(this).metadata().page);
				return false;
			})
			
			if(count > 1){
				//prev.fadeIn();
				//next.fadeIn();
				pages.fadeIn();
			}
			
			
			
		
			//bind buttons
			next.click(function(){
				resetInterval();
				next_slide(); 
				return false;
			});
			prev.click(function(){
				resetInterval();
				prev_slide(); 
				return false;
			});
			showInfo();
			
			resetInterval();
	}
	
	function resetInterval(){
		if(interval)
			clearInterval(interval);
		
		interval = setInterval(next_slide,8000);
	}
	
	
	function move_to_slide(page){
		jump = page;
		if(slides.find('li:first').metadata().page == page){
			//do nothing
			jump = 0;
		}else if(slides.find('li:first').metadata().page > page){
			prev_slide();
		}else if(slides.find('li:first').metadata().page < page){
			next_slide();
		}
	}
	
	function next_slide(){
		if(locked)
			return;
		
		hideInfo();	
		slides.find('li:first').animate({marginLeft:'-'+slides.find('li:first').width() +'px'},800,"swing", function(){
			slides.append(slides.find('li:first'));	
			slides.find('li:last').css('margin-left','0px');
			showInfo();
			
			if(jump != 0){
				
				if(slides.find('li:first').metadata().page == jump)
					jump = 0;
				else
					next_slide();
			}
			
		});			
	}
	
	function prev_slide(){
		if(locked)
			return;
		
		hideInfo();	
		slides.find('li:last').css('margin-left','-'+slides.find('li:last').width() +'px');
		slides.prepend(slides.find('li:last'));
		
		slides.find('li:first').animate({marginLeft:'0px'},800,"swing", function(){
			showInfo();
			
			if(jump != 0){
				if(slides.find('li:first').metadata().page == jump)
					jump = 0;
				else
					prev_slide();
			}
		});
		
	}
	
	function hideInfo(){
		locked = true;	
	}
	
	function showInfo(){
		//text.html('<span class="green">Artist:</span> <a href="'+slides.find('li:first').metadata().url+'">'+slides.find('li:first').metadata().text+'</a>');
		pages.find('a').removeClass('active');
		pages.find('.page_'+slides.find('li:first').metadata().page).addClass('active');
		locked = false;
	}
	
	init();

};

jQuery.fn.bambuserDynamic = function(){
	
	
	if($(this).length != 1){
		$(this).each(function(){
			$(this).bambuserDynamic();
		});
		return;
	}
	
	$(this).click(function(){
		
		if(!$(this).hasClass('bambuserActive')){
			$('.bambuserActive').each(function(){
				var url = $(this).metadata().prevUrl;
				$(this).html('<img width="140" height="115" src="'+url+'"/>');
				$(this).css('width','140px');
				$(this).css('height','115px');
				$(this).removeClass('bambuserActive');
			});
			
			$(this).parent('.day').prepend($(this));
			
			var id = $(this).metadata().vId;
			var width = "290";
			var height = "230";
			var embed = '<object id="bplayer" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+width+'" height="'+height+'"><embed name="bplayer" src="http://bambuser.com/r/player.swf?vid='+id+'" type="application/x-shockwave-flash" flashvars="autostart=yes" width="'+width+'" height="'+height+'" allowfullscreen="true" wmode="opaque"></embed><param name="movie" value="http://bambuser.com/r/player.swf?vid='+id+'"></param><param name="allowfullscreen" value="true"></param><param name="flashvars" value="autostart=yes"></param><param name="wmode" value="opaque"></param></object>';
			$(this).html(embed);
			$(this).css('width',width+'px');
			$(this).css('height',height+'px');
			$(this).addClass('bambuserActive');
			
		}
	});
}


jQuery.fn.fixUploadFields = function(){
	if($(this).length != 1){
		$(this).each(function(){
			$(this).fixUploadFields();
		});
		return;
	}
	
	var text = $(this).find('.dummyText');
	
	$(this).find('.uploadField').change(function(){
		text.val($(this).val());
	});
	
}


/* blog competition post functions */

function competitionPrePost(form){
	$('#blog .competition .loader').fadeIn('fast');
}

function competitionValidationError(form){
	alert('Alla fälten i formuläret måste fyllas i, även en fil måste bifogas.');
}

function competitionPostError(arg1, arg2, arg3){
	alert('Vi har förnärvarande problem med att kontakta servern, om problemet uppstår igen ta kontakt med oss via johan@sjmelodifestivalen.se');
	$('#blog .competition .loader').fadeOut('fast');
}

function competitionPostSuccess(data){
	if(data){
	$('#blog .competition').slideUp('slow', function(){
		$('#blog .competition').html('Tack!');
		$('#blog .competition').slideDown('slow');
	});
	}else{
		alert("Upladdningen gick inte igenom, vi tillåter följande format: 'jpg', 'gif', 'png', 'jpeg', 'pdf', 'mov', 'mpeg', 'mpg', 'avi', 'xvid', 'flv' och filen får max vara 19mb.");
		$('#blog .competition .loader').fadeOut('fast');
	}
}


$(document).ready(function(){
	
	
	$('.bambuserVideo').bambuserDynamic();
	
	//bind all slideshows
	//$('.follow .artist .browse').browseArtist();
	$('.top .turne').slideshow();
	
	//twitter
	/*
	$(".twitter-content").getTwitter({
		userName: "SJ_AB",
		numTweets: 30,
		loaderText: "Loading tweets...",
		slideIn: false,
		showHeading: false,
		headingText: "Latest Tweets",
		showProfileLink: true
	});
	*/
	$('.subpage-page-turneschema .map div').mouseenter(function(){
		if ($.browser.msie && $.browser.version.substring(0,1) === '6') {

		}else{
			if(!$(this).hasClass('active')){
				$(this).removeClass('normal');
				$(this).addClass('super');
			}	
		}
	});
	
	$('.subpage-page-turneschema .map div').mouseleave(function(){
		if ($.browser.msie && $.browser.version.substring(0,1) === '6') {

			
		
		}else{
			if(!$(this).hasClass('active')){
				$(this).removeClass('super');
				$(this).addClass('normal');
			}	
		}
	});
	
	$('.subpage-page-turneschema .map div').click(function(){
		window.location.href = '/turneschema/' + $(this).metadata().city;
	});
	
	$('.votebar .bar').each(function(){
		var new_width = $(this).css('width');
		$(this).css('width','0%');
		$(this).css('display','block');
		$(this).animate( { width:new_width }, { queue:false, duration:3000 } );
		
	});
	
	/* blog */
	
	$('.openCompetition').click(function(){
		$('.competition').slideToggle('slow');
		return false;
	});
	
	$('.fileUploadHolder').fixUploadFields();
	
	$('#blog .entry-content a').each(function(){
		if($(this).attr('target') == '')
			$(this).attr('target','_blank');
	});
	
});



/**
 * jQuery.query - Query String Modification and Creation for jQuery
 * Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
 * Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
 * Date: 2009/8/13
 *
 * @author Blair Mitchelmore
 * @version 2.1.7
 *
 **/
new function(settings) { 
  // Various Settings
  var $separator = settings.separator || '&';
  var $spaces = settings.spaces === false ? false : true;
  var $suffix = settings.suffix === false ? '' : '[]';
  var $prefix = settings.prefix === false ? false : true;
  var $hash = $prefix ? settings.hash === true ? "#" : "?" : "";
  var $numbers = settings.numbers === false ? false : true;
  
  jQuery.query = new function() {
    var is = function(o, t) {
      return o != undefined && o !== null && (!!t ? o.constructor == t : true);
    };
    var parse = function(path) {
      var m, rx = /\[([^[]*)\]/g, match = /^([^[]+)(\[.*\])?$/.exec(path), base = match[1], tokens = [];
      while (m = rx.exec(match[2])) tokens.push(m[1]);
      return [base, tokens];
    };
    var set = function(target, tokens, value) {
      var o, token = tokens.shift();
      if (typeof target != 'object') target = null;
      if (token === "") {
        if (!target) target = [];
        if (is(target, Array)) {
          target.push(tokens.length == 0 ? value : set(null, tokens.slice(0), value));
        } else if (is(target, Object)) {
          var i = 0;
          while (target[i++] != null);
          target[--i] = tokens.length == 0 ? value : set(target[i], tokens.slice(0), value);
        } else {
          target = [];
          target.push(tokens.length == 0 ? value : set(null, tokens.slice(0), value));
        }
      } else if (token && token.match(/^\s*[0-9]+\s*$/)) {
        var index = parseInt(token, 10);
        if (!target) target = [];
        target[index] = tokens.length == 0 ? value : set(target[index], tokens.slice(0), value);
      } else if (token) {
        var index = token.replace(/^\s*|\s*$/g, "");
        if (!target) target = {};
        if (is(target, Array)) {
          var temp = {};
          for (var i = 0; i < target.length; ++i) {
            temp[i] = target[i];
          }
          target = temp;
        }
        target[index] = tokens.length == 0 ? value : set(target[index], tokens.slice(0), value);
      } else {
        return value;
      }
      return target;
    };
    
    var queryObject = function(a) {
      var self = this;
      self.keys = {};
      
      if (a.queryObject) {
        jQuery.each(a.get(), function(key, val) {
          self.SET(key, val);
        });
      } else {
        jQuery.each(arguments, function() {
          var q = "" + this;
          q = q.replace(/^[?#]/,''); // remove any leading ? || #
          q = q.replace(/[;&]$/,''); // remove any trailing & || ;
          if ($spaces) q = q.replace(/[+]/g,' '); // replace +'s with spaces
          
          jQuery.each(q.split(/[&;]/), function(){
            var key = decodeURIComponent(this.split('=')[0] || "");
            var val = decodeURIComponent(this.split('=')[1] || "");
            
            if (!key) return;
            
            if ($numbers) {
              if (/^[+-]?[0-9]+\.[0-9]*$/.test(val)) // simple float regex
                val = parseFloat(val);
              else if (/^[+-]?[0-9]+$/.test(val)) // simple int regex
                val = parseInt(val, 10);
            }
            
            val = (!val && val !== 0) ? true : val;
            
            if (val !== false && val !== true && typeof val != 'number')
              val = val;
            
            self.SET(key, val);
          });
        });
      }
      return self;
    };
    
    queryObject.prototype = {
      queryObject: true,
      has: function(key, type) {
        var value = this.get(key);
        return is(value, type);
      },
      GET: function(key) {
        if (!is(key)) return this.keys;
        var parsed = parse(key), base = parsed[0], tokens = parsed[1];
        var target = this.keys[base];
        while (target != null && tokens.length != 0) {
          target = target[tokens.shift()];
        }
        return typeof target == 'number' ? target : target || "";
      },
      get: function(key) {
        var target = this.GET(key);
        if (is(target, Object))
          return jQuery.extend(true, {}, target);
        else if (is(target, Array))
          return target.slice(0);
        return target;
      },
      SET: function(key, val) {
        var value = !is(val) ? null : val;
        var parsed = parse(key), base = parsed[0], tokens = parsed[1];
        var target = this.keys[base];
        this.keys[base] = set(target, tokens.slice(0), value);
        return this;
      },
      set: function(key, val) {
        return this.copy().SET(key, val);
      },
      REMOVE: function(key) {
        return this.SET(key, null).COMPACT();
      },
      remove: function(key) {
        return this.copy().REMOVE(key);
      },
      EMPTY: function() {
        var self = this;
        jQuery.each(self.keys, function(key, value) {
          delete self.keys[key];
        });
        return self;
      },
      load: function(url) {
        var hash = url.replace(/^.*?[#](.+?)(?:\?.+)?$/, "$1");
        var search = url.replace(/^.*?[?](.+?)(?:#.+)?$/, "$1");
        return new queryObject(url.length == search.length ? '' : search, url.length == hash.length ? '' : hash);
      },
      empty: function() {
        return this.copy().EMPTY();
      },
      copy: function() {
        return new queryObject(this);
      },
      COMPACT: function() {
        function build(orig) {
          var obj = typeof orig == "object" ? is(orig, Array) ? [] : {} : orig;
          if (typeof orig == 'object') {
            function add(o, key, value) {
              if (is(o, Array))
                o.push(value);
              else
                o[key] = value;
            }
            jQuery.each(orig, function(key, value) {
              if (!is(value)) return true;
              add(obj, key, build(value));
            });
          }
          return obj;
        }
        this.keys = build(this.keys);
        return this;
      },
      compact: function() {
        return this.copy().COMPACT();
      },
      toString: function() {
        var i = 0, queryString = [], chunks = [], self = this;
        var encode = function(str) {
          str = str + "";
          if ($spaces) str = str.replace(/ /g, "+");
          return encodeURIComponent(str);
        };
        var addFields = function(arr, key, value) {
          if (!is(value) || value === false) return;
          var o = [encode(key)];
          if (value !== true) {
            o.push("=");
            o.push(encode(value));
          }
          arr.push(o.join(""));
        };
        var build = function(obj, base) {
          var newKey = function(key) {
            return !base || base == "" ? [key].join("") : [base, "[", key, "]"].join("");
          };
          jQuery.each(obj, function(key, value) {
            if (typeof value == 'object') 
              build(value, newKey(key));
            else
              addFields(chunks, newKey(key), value);
          });
        };
        
        build(this.keys);
        
        if (chunks.length > 0) queryString.push($hash);
        queryString.push(chunks.join($separator));
        
        return queryString.join("");
      }
    };
    
    return new queryObject(location.search, location.hash);
  };
}(jQuery.query || {}); // Pass in jQuery.query as settings object


//cookie

function getCookie(cookie_name){
	  var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );
	
	  if(results)
	    return (unescape(results[2]));
	  else
	    return null;
}
function setCookie( name, value, exp_y, exp_m, exp_d, path, domain, secure ){
	  var cookie_string = name + "=" + escape ( value );
	
	  if(exp_y){
	    var expires = new Date(exp_y, exp_m, exp_d);
	    cookie_string += "; expires=" + expires.toGMTString();
	  }
	
	  if(path)
	        cookie_string += "; path=" + escape(path);
	
	  if(domain)
	        cookie_string += "; domain=" + escape(domain);
	  
	  if(secure)
	        cookie_string += "; secure";
	 
	  document.cookie = cookie_string;
}
