﻿var tabs = {
				
	toolsApi : null,
	current : null,
	tabCounter : -1,
	
	init : function() {
		
		var tabsContainer = $("<div id='tabs'></div>").insertBefore(".panes");
		var ul = $("<ul/>").appendTo(tabsContainer);
		var items = $(".panes > h1");
		items.each(function(i) {
			var el = $(this);
			var name = el.html();
			var id = el.attr("id");
			var li = $('<li/>');
			var a = $('<a/>').attr('href', '#'+id).
				addClass(tabs.map.getValue(id).inactive).
				addClass("LnkBase").
				append("<span>"+name+"</span>");
			li.append(a);
			ul.append(li);
			el.remove();
		}); 
   		
		// Hide all tab panes initially
		$(".panes > div").css("display", "none");
		// Setup jquery tools tabs
		tabs.toolsApi = $("#tabs ul").tabs(".panes > div").history({api:true}); 
		// Update style on first selected tab
		tabs.updateStyles(tabs.toolsApi.getCurrentTab());
		// Update style on tab clicks
		tabs.toolsApi.bind("onClick", function(e, tabIndex) {
			var elm = e.originalTarget || e.srcElement;
			tabs.updateStyles($(elm));
		});
	},
	
	registerTab : function(id, cssInactive, cssActive){
		tabs.map.put(id, {inactive:cssInactive, active:cssActive})
	},
	
	updateStyles : function(elm) {
		var obj;
		if (tabs.current != null) {
			obj = tabs.map.getValue(tabs.current.attr("href").substr(1));
			tabs.current.removeClass(obj.active);
			tabs.current.addClass(obj.inactive);
		}
		
		obj = tabs.map.getValue(elm.attr("href").substr(1));
		elm.removeClass(obj.inactive);
		elm.addClass(obj.active);
		tabs.current = elm;
	},

	map: {
		dict : {},
		put : function(key, obj) {
			tabs.map.dict[key] = obj;
		},
		getValue : function(key) {
			return tabs.map.dict[key];
		}
	}
};

var ratings = {
	
	init : function(movieId, msgCount, msgRating) {
		
		ratings.movieId = movieId;
		ratings.msgCount = msgCount;
		ratings.msgRating = msgRating;
	
		//$("<div class='popup ratingTips'><div class='content'><p></p></div></div>").appendTo('div.rating ul.rating');
        $('ul.rating li a').each(function(index) {
            $(this).bind('click', function(e) {
				ratings.rate(index+1, e.pageX, e.pageY);
            })
            /*
            var tipsTextHeading = $(this).attr('title');
            var tipsTextDescription = $(this).text();

            $(this).hover(function() {
                var $ratePopup = $(this).parent().parent();

                var posX = (-1 * ($ratePopup.find('a').index($(this)) * 14) + 22);

                $('.ratingTips').css({ right: posX });
                $('.ratingTips').show();
                $('.ratingTips p').html('<strong>' + tipsTextHeading + '</strong><br/><span class="description">' + tipsTextDescription + '</span>');
                $(this).attr('title', '');
            }, function() {
                $('.ratingTips').hide();
                $('.ratingTips p').text();
                $(this).attr('title', tipsTextHeading);
            });
            */
        });
        $('ul.rating').hover(function() {
            $(this).css({ 'background-image': 'none' });
        }, function() {
            $(this).css({ 'background-image': 'url(/Layout/NSU/Schemes/Watch/rating.png)' });
        });
	},
	
	rate : function(v, x, y) {
		var co = $.cookie('MovieRating');
        if (co == null) {co = '';}
        if (co.indexOf('|' + ratings.movieId + '|') < 0) {
            $.post(
		         "/Services/Watch/Rating.ashx",
		        { movieId: ratings.movieId, value: v },
			    function(data, textStatus) {
					if (data == null || data.ErrorHeading) {
			            ratings.showFeedback(ratings.msgRating[2], x, y);
					} else {
						ratings.showFeedback(ratings.msgRating[0], x, y);
						var ci = 1;
		                if (data.NumberOfRatings == 1) { ci = 0; }
		                $('div.ratingStatus .ratingCountText').text(ratings.msgCount[ci]);
		                $('div.ratingStatus .ratingCount').text(data.NumberOfRatings);
		                $('div.rating ul.rating').removeAttr('class').attr('class', 'rating rating' + data.AverageRating + '');
		                $.cookie('MovieRating', co + '|' + ratings.movieId + '|', {expires:365});
					}
			    },
			   "json"
		    );
        }
        else {
            ratings.showFeedback(ratings.msgRating[1], x, y);
        }
	},
	
	showFeedback : function(msg, x, y) {
		var fb = $('.rating > .feedback');
		fb.css({
			left : Math.max(2, x - 28) + "px",
			top : (y - parseInt(fb.css("height")) - 8) + "px"
		})
		fb.show();
		fb.html('<div class="content"><p>' + msg + '</p></div>');
		
		// No fade for ie because the background is a png with alpha transparency
		if (jQuery.browser.msie) 
			setTimeout("$('.rating > .feedback').hide()", 2000);
		else
			setTimeout("$('.rating > .feedback').fadeOut('slow')", 2000);
			               
	}
}

var infoPopup = {

	CLOSED_WIDTH : 57,
	
	closed : true,
	
	init : function(btnLabel) {
		
		// Store jquery ref to popup div
		var target = this.target = $("#infopopup");
		
		// Add open/close button
		var btn = $('<div/>').prependTo(target).
			html('<span>' + btnLabel.replace(/(.)/g,"$1<br/>") + '</span>').
			addClass("toggle");

		// Vertically center button text
		btn.find("span").css({
			"top" : (btn.height()/2 - btn.find("span").height()/2)-3 + "px",
			"background-position" : "0px " + (btn.find("span").height()/2 - 4) + "px"
		});
		
		// Append invisible anchor to btn div
		$('<a href="#"/>').appendTo(btn).bind("click", function(){ infoPopup.toggle(); return false; });
		
		// Vertically center content
		target.find(".content").css({
			"padding-top" : 0,
			"top" : (target.height()/2 - target.find(".content").height()/2) + "px"
		});
		
		// Switch classes on target
		target.removeClass("infopopup").addClass("infopopped");
		
		// Store object with css for target in open and closed state
		this.css = {
			closed: {
				"clip" : "rect(0px, "+this.CLOSED_WIDTH+"px, "+target.height()+"px, 0px)",
				"left" : $("#grid").width() + parseInt($("#grid").css("padding-right")) - btn.width() - 20
			},
			open : {
				"clip" : "rect(0px, "+(target.width()-5)+"px, "+target.height()+"px, 0px)",
				"left" : $("#grid").width() + parseInt($("#grid").css("padding-right")) - target.width() + 5 //was +5
			}
		} 
		
		// Start closed
		target.css(this.css.closed);
		
		// Toggle opened when no session cookie . added path: "/" to make it a sitewide cookie/Martin N
		var co = $.cookie("MovieInfoSeen");
        if (co != "foo") {
			$.cookie("MovieInfoSeen","foo",{path: '/' });
			this.toggle();
		}
	},
	
	toggle : function() {
		if (this.closed) {
			this.target.find(".toggle span").addClass("open");
			this.target.stop().animate(this.css.open, 800);
		} else {
			this.target.find(".toggle span").removeClass("open");
			this.target.stop().animate(this.css.closed, 800);
		}
		this.closed = !this.closed;
	}
};




/**
 * jQuery animate clip plugin
 * http://plugins.jquery.com/project/clipFX
 * @author alexander.farkas
 * @version 1.0
 */
(function($){
	
	if(!document.defaultView || !document.defaultView.getComputedStyle){ // IE6-IE8 workaround
		var oldCurCSS = $.curCSS;
		$.curCSS = function(elem, name, force){
			var curStyle = elem.currentStyle, ret;
			if(name === 'font-size'){
				name = 'fontSize';
			}
			if((name !== 'clip' && name !== 'fontSize') || !curStyle){
				return oldCurCSS.apply(this, arguments);
			}
			var style = elem.style;
			if ( !force && style ){
				ret = style[ name ];
			}
			if(name === 'clip'){
				ret = ret || 'rect('+ (curStyle.clipTop || 'auto') +' '+ (curStyle.clipRight || 'auto') +' '+ (curStyle.clipBottom || 'auto') +' '+ (curStyle.clipLeft || 'auto') +')';
			} else {
				ret = ret || curStyle.fontSize;
				if(!(/px/.test(ret))){
					// Remember the original values
					var width = style.width, rsWidth = elem.runtimeStyle.width;
	
					// Put in the new values to get a computed value out
					elem.runtimeStyle.width = elem.currentStyle.width;
					style.width = '100em';
					ret = style.pixelWidth / 100 + "px";
					// Revert the changed values
					style.width = width;
					elem.runtimeStyle.width = rsWidth;
				}
			}
			return ret;
		};
	}
})(jQuery);

(function($){
	var calcClipAuto = [
		function(){
			return 0;
		},
		function(elem){
			return $(elem).outerWidth();
		},
		function(elem){
			return $(elem).outerHeight();
		},
		function(elem){
			return 0;
		}
	],
					
	calcNumClip = function(prop, elem){
		return ((/em/.test(prop))) ? 
				(parseFloat($.curCSS(elem, 'fontSize'), 10) || 1) * (parseFloat(prop, 10) || 0) :
				(parseInt(prop, 10) || 0);
	};
	
	var calcClip = function(css, fx, isEnd){
		var ret 	= [];
		if(css === 'auto'){
			css = 'rect(auto auto auto auto)';
		}
		
		css = css.replace(/rect\(|\)/g, '').split(/,\s*|\s/);
		if(isEnd){
			fx.endClipStyle = 'rect('+ css.join(' ') +')';
		}
		for(var i = 0; i < css.length; i++){
			ret[i] = (css[i] !== 'auto') ? 
						calcNumClip(css[i], fx.elem) : 
						calcClipAuto[i](fx.elem);
		}
		
		return ret;
	};
	
	jQuery.fx.step.clip = function(fx){
		if (!fx.clipInit) {
			
			fx.start = calcClip($.curCSS(fx.elem, 'clip'), fx);
			fx.end = calcClip(fx.end, fx, true);
			fx.elmStyle = fx.elem.style;
			fx.clipInit = true;
		}
		
		fx.elmStyle.clip = 'rect('+ ( fx.pos * (fx.end[0] - fx.start[0]) + fx.start[0] ) +'px '+ (fx.pos * (fx.end[1] - fx.start[1]) + fx.start[1]) +'px '+ (fx.pos * (fx.end[2] - fx.start[2]) + fx.start[2]) +'px '+ (fx.pos * (fx.end[3] - fx.start[3]) + fx.start[3]) +'px)';
		
		if(fx.pos === 1 && fx.endClipStyle){
			fx.elmStyle.clip = fx.endClipStyle;
		}
	};
})(jQuery);

//Competion Mode vate handeling
var validate = {
    email: function(value) {
        return value.match(/^.+@.+\..+$/) ? true : false;
    }
};
$.fn.showErrors = function(args) {
    var opt = jQuery.extend({
        email: "Du måste ange en korrekt epostadress"
    }, args);
    $(this).each(function() {
        var input = $(this);
        var errormsg = $(this).prev('.errormsg').length ? $(this).prev('.errormsg') : $('<div class="errormsg"></div>');
        if (input.is('.invalid-email')) {
            errormsg.text(opt.email);
        } else if (input.is('[type=text]')) {
            errormsg.text(opt.text);
        }
        if (input.is('[type=password].empty')) {
            input.prev('.replacement').addClass('invalid').removeClass('empty');
        }
        errormsg.insertBefore(input.removeClass('empty'));
    });
    return this;
};


$.fn.initforms = function() {
    var container = $(this);
    $('input:radio', container).parent('label').click(function() {
        $('label.selected input[type=radio][name=' + $(this).find('input[type=radio]').attr('name') + ']', container).parent().removeClass('selected');
        $(this).addClass('selected');
    });
    $('input:radio:checked', container).parent('label').addClass('selected');
    $('input.email', container).bind('validate', function() {
        if (!validate.email(this.value)) {
            $(this).addClass('invalid invalid-email');
        } else {
            $(this).removeClass('invalid-email');
        }
    });
    $('input[required]', container).addClass('invalid');
    $('input', container).bind('keyup click focus blur change', function() {
        var input = $(this);
        input.removeClass('valid').trigger('validate');
        if (!input.is('[type=radio]') && !input.is('[type=checkbox]')) {
            if (input.val().length && !input.is('.placeholder')) {
                input.removeClass('empty');
                if (!input.is('.invalid-email') && !input.is('.invalid-number') && !input.is('.invalid-tel') && !input.is('.invalid-date') && !input.is('.invalid-url') && !input.is('.placeholder') && !input.is('.invalid-pattern')) {
                    input.removeClass('invalid').addClass('valid').next('.errormsg').remove();
                }
            } else {
                input.addClass('empty');
            }
        }
    }).trigger('change');
    $('fieldset [type=submit]', container).click(function() {
        var fieldset = $(this).closest('fieldset');
        if (fieldset.find('[required].invalid, [required].empty').length) {
            fieldset.find('[required].invalid, [required].empty').showErrors({ 'email': WATCH.EmailMessages.email });
            return false;
        }
    });
    $('a.facebook-share', container).click(function() {
        window.open(this.href, "mywindow", "menubar=0,resizable=1,width=600,height=500");
        return false;
    });    
};
$.fn.ajaxPost = function(targetid) {
    var container = $(this);
    var form = $('form', container);
    form.submit(function() {
        container.addClass('loading');
        $.post(form.attr('action'), $(this).serialize() + '&' + form.find('[type=submit]').attr('name') + '=', function(data) {
            container.removeClass('loading');
            form.html($('#' + targetid, data)).append($('input[type=hidden]', data));
            container.initforms();
            $('html').animate({ scrollTop: container.css('top').split('px')[0] - 50 }, 800);
        });
        return false;
    });
};

$(document).ready(function() {
    $('a.lightbox').lightbox({}, function() {
        $('#lightbox').initforms();
        $('#lightbox').ajaxPost('moviecontent');
        $('#lightbox .movielist li h3 a').each(function() {
            var movietitle = $(this);
            if (movietitle.text().length > 32) {
                var titletext = movietitle.text();
                movietitle.attr('title', titletext).text(titletext.substr(0, 32) + '...');
            }
        });        
    });
    $('a.light').lightbox({"class":"light"}, function() {
		$("#lightbox a.close").hide();
		$("#lightbox .inner").hide();
		$("#lightbox").addClass("white");
         	$('#lightbox').animate({"width":"400px","marginLeft":"-200px"},200,function(){
				$("#lightbox a.close").show();
				$("#lightbox .inner").slideDown(900);
			});
    });
});

