/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('n.5=v(a,b,c){4(7 b!=\'w\'){c=c||{};4(b===o){b=\'\';c=$.x({},c);c.3=-1}2 d=\'\';4(c.3&&(7 c.3==\'p\'||c.3.q)){2 e;4(7 c.3==\'p\'){e=y z();e.A(e.B()+(c.3*C*r*r*D))}s{e=c.3}d=\'; 3=\'+e.q()}2 f=c.8?\'; 8=\'+(c.8):\'\';2 g=c.9?\'; 9=\'+(c.9):\'\';2 h=c.t?\'; t\':\'\';6.5=[a,\'=\',E(b),d,f,g,h].F(\'\')}s{2 j=o;4(6.5&&6.5!=\'\'){2 k=6.5.G(\';\');H(2 i=0;i<k.m;i++){2 l=n.I(k[i]);4(l.u(0,a.m+1)==(a+\'=\')){j=J(l.u(a.m+1));K}}}L j}};',48,48,'||var|expires|if|cookie|document|typeof|path|domain|||||||||||||length|jQuery|null|number|toUTCString|60|else|secure|substring|function|undefined|extend|new|Date|setTime|getTime|24|1000|encodeURIComponent|join|split|for|trim|decodeURIComponent|break|return'.split('|'),0,{}))

/**
 * SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
if(typeof deconcept=="undefined"){var deconcept=new Object();}if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params=new Object();this.variables=new Object();this.attributes=new Array();if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},setAttribute:function(_e,_f){this.attributes[_e]=_f;},getAttribute:function(_10){return this.attributes[_10];},addParam:function(_11,_12){this.params[_11]=_12;},getParams:function(){return this.params;},addVariable:function(_13,_14){this.variables[_13]=_14;},getVariable:function(_15){return this.variables[_15];},getVariables:function(){return this.variables;},getVariablePairs:function(){var _16=new Array();var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;},getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";var _1a=this.getParams();for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}var _1c=this.getVariablePairs().join("&");if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";var _1d=this.getParams();for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}var _1f=this.getVariablePairs().join("&");if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}return _19;},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true);this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;}if(this.major>fv.major){return true;}if(this.minor<fv.minor){return false;}if(this.minor>fv.minor){return true;}if(this.rev<fv.rev){return false;}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;






/* CONFIG */

(function($) {

    var trailing_whitespace = true;

    $.fn.truncate = function(options) {

        var opts = $.extend({}, $.fn.truncate.defaults, options);

        $(this).each(function() {

            var content_length = $.trim(squeeze($(this).text())).length;
            if (content_length <= opts.max_length)
                return;  // bail early if not overlong

            var actual_max_length = opts.max_length - opts.more.length - 3;  // 3 for " ()"    
            var truncated_node = recursivelyTruncate(this, actual_max_length);
            var full_node = $(this);

            truncated_node.insertAfter(full_node);
            // This is an ugly approximation for getting the last block tag:
            // we just pick the last <p> or else the container itself.
            truncated_node.find('p:last').add(truncated_node).eq(0).append(' <a href="#show more content">' + opts.more + '</a>');

            full_node.hide();
            full_node.find('p:last').add(full_node).eq(0).append(' <a href="#show less content">' + opts.less + '</a>');

            full_node.parent().click(function() {
                truncated_node.toggle();
                full_node.toggle();
                return false;
            })
            .hover(function() {
                $(this).addClass(opts.hoverClass);
            }, function() {
                $(this).removeClass(opts.hoverClass);
            });
        });
    }

    // Note that the "more" link and its wrapping counts towards the max length:
    // so "more" and a max length of 10 might give "123 (more)"
    $.fn.truncate.defaults = {
        max_length: 100,
        more: ' more...',
        less: 'less',
        hoverClass: 'hover'
    };

    function recursivelyTruncate(node, max_length) {
        return (node.nodeType == 3) ? truncateText(node, max_length) : truncateNode(node, max_length);
    }

    function truncateNode(node, max_length) {
        var node = $(node);
        var new_node = node.clone().html("");
        node.contents().each(function() {
            var remaining_length = max_length - new_node.text().length;
            if (remaining_length == 0) return;
            new_node.append(recursivelyTruncate(this, remaining_length));
        });
        return new_node;
    }

    function truncateText(node, max_length) {
        var text = squeeze(node.data);
        if (trailing_whitespace)  // remove initial whitespace if last text
            text = text.replace(/^ /, '');  // node had trailing whitespace.
        trailing_whitespace = !!text.match(/ $/);
        var text = text.slice(0, max_length);
        // Ensure HTML entities are encoded
        // http://debuggable.com/posts/encode-html-entities-with-jquery:480f4dd6-13cc-4ce9-8071-4710cbdd56cb
        text = $('<div/>').text(text).html();
        return text;
    }

    // Collapses a sequence of whitespace into a single space.
    function squeeze(string) {
        return string.replace(/\s+/g, ' ');
    }

})(jQuery);


function preloadImages()
{
	var d=document; if(d.images)
	{ 
		if(!d.p) d.p=new Array();
		var i,j=d.p.length,a=preloadImages.arguments; for(i=0; i<a.length; i++)
		if (a[i].indexOf("#")!=0)
		{ 
			d.p[j]=new Image; d.p[j++].src=a[i];
		}
	}
}

function createCookie(name,value,days)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name)
{
	createCookie(name,"",-1);
}

function removeOverlay()
{
	
	$('#overlay').fadeOut(300,function(){
		$(this).remove();
	});
}

function switchStylestyle(styleName)
{

	$('body').append('<div id="overlay" />');
	$('body').css({height:'100%'});
	$('#overlay')
	.css({
		display: 'none',
		position: 'absolute',
		top:0,
		left: 0,
		width: '100%',
		height: '100%',
		zIndex: 1000,
		background: 'black url(/static/images/ulstein_loader.gif) no-repeat center'
	})
	.fadeIn(300,function(){

		$('link[@rel*=style][title]').each(function(i) 
		{
			this.disabled = true;
			if (this.getAttribute('title') == styleName) this.disabled = false;

		});
		createCookie('style', styleName, 365);
						
		setTimeout(removeOverlay, 2000);

	});
}

jQuery.fn.iphoneSwitch = function(start_state, options) {


	$('link[@rel*=style][title]').each(function(i) 
	{
		this.disabled = true;
		if (this.getAttribute('title') == start_state) this.disabled = false;
	});

	var state = start_state == 'off' ? start_state : 'on';

	var settings = {
		switch_on_container_path: 'http://www.ulsteinlab.com/static/images/switch_container.png',
		switch_off_container_path: 'http://www.ulsteinlab.com/static/images/switch_container.png',
		switch_path: 'http://www.ulsteinlab.com/static/images/switch_image.png',
		switch_height: 30,
		switch_width: 58
	};

	if(options) {
		jQuery.extend(settings, options);
	}

	return this.each(function() 
	{
		var container;
		var image;
		
		container = jQuery('<div class="iphone_switch_container" style="height:'+settings.switch_height+'px; width:'+settings.switch_width+'px; position: relative; overflow: hidden"></div>');

		image = jQuery('<img class="iphone_switch" style="height:'+settings.switch_height+'px; width:'+settings.switch_width+'px; background-image:url('+settings.switch_path+'); background-repeat:none; background-position:'+(state == 'on' ? 0 : -34)+'px" src="'+(state == 'on' ? settings.switch_on_container_path : settings.switch_off_container_path)+'" />');

		jQuery(this).html(jQuery(container).html(jQuery(image)));

		jQuery(this).click(function() {
			
			state = readCookie('style');
			
			if(state == 'on') {
				state = 'off';
				
				
				jQuery(this).find('.iphone_switch').animate({backgroundPosition: -34}, "slow", function() {
					switchStylestyle(state);
					jQuery(this).attr('src', settings.switch_off_container_path);
					
					return false;
				});

			}
			else {
				state = 'on';
			
				jQuery(this).find('.iphone_switch').animate({backgroundPosition: 0}, "slow", function() {
					switchStylestyle(state);
					jQuery(this).attr('src', settings.switch_on_container_path);
					
					return false;
				});
				
			}
		});
	});
};


/* 	SITE CONFIG -----------------------------------------------------------------------
*/


$(document).ready(function() {

	$('#hidden-content').hide();
	
	$('.note').truncate({ max_length: 150 }); 
	
	var tabContainers = $('div.tabs > div');

	$('div.tabs ul.tabNavigation a').click(function () {
		tabContainers.hide().filter(this.hash).fadeIn('slow');
		$('div.tabs ul.tabNavigation a').removeClass('selected');
		$(this).addClass('selected');

		return false;
	}).filter(':first').click();
	
	
	if(!readCookie('style')) createCookie('style', 'off', 365);
	var c;
	c = readCookie('style') ? readCookie('style') : 'off';
	
	
	
	$('#switch').iphoneSwitch(c);

	$('#hidden-content').hide();

	setTimeout('preloadImages(\'http://ulsteinlab/static/images/ulstein_loader.gif\')', 8000);


	$('#toggle').toggle(
		function() {
			$(this).addClass('toggle-switch');
		}, 
		function() {
			$(this).removeClass('toggle-switch');
		}
	);
	
});



$(function(){
	
	function playThisVideo(id)
	{	$('#flashplayer').show();
		var so = new SWFObject("http://www.ulsteinlab.com/static/animations/videoplayer.swf", "flashplayer", "800", "508", "9", "#ffffff");
		so.addParam("wmode", "transparent");
		so.addVariable("introImage", 'http://www.ulsteinlab.com/static/images/-dummy.jpg');
		so.addVariable("autoPlayVideo", true);
		so.addVariable("getPath", '/static/videos/streams/' + id);
		so.write("flashplayer");
	}

	var videoId = '';
	$('#films .play, #animations .play').click(function() {
		
		$('#flashplayer').hide();
		
		var videoId = $(this).attr('rel').split('movieID-')[1];
		
		$.post("/page/movie", { videoID: videoId },
	  	
		function(data){
		
			$('#main-header').html(data.title);
			
			$('html, body').animate({scrollTop:0}, 'slow', function(){
				playThisVideo(data.movie_stream);
			});
			

		}, "json");

		return false;
	});
	
	$('.backtotop').click(function(){
			$('html, body').animate({scrollTop:0}, 'slow');
	});
	
})

