jQuery.fn.reverse = Array.prototype.reverse;
String.prototype.linkify = function(cl) { return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g, function(m) { m = m.link(m); m = m.replace('href="',' target="_blank" href="'); return m; }); };
String.prototype.linkifynames = function(cl) { return this.replace(/(@[A-Za-z]+)/g, '<a href="http://twitter.com/$1" target="_blank">$1</a>') };
var months = new Array("Tammikuu", "Helmikuu", "Maaliskuu", "Huhtikuu", "Toukokuu", "KesÃ¤kuu", "HeinÃ¤kuu", "Elokuu", "Syyskuu", "Lokakuu", "Marraskuu", "Joulukuu" );

var mode = true;

$(document).ready( init );

function init() {
	checkWindowSize();
	initOurWork();
	initTweet();
	tagArchive();
	showRightTag();
	$('.case-meta ul a').attr('target', '_blank');
	$('.share a').attr('target', '_blank');
	prepareBigPicture();
	followUsColors();
}


function checkWindowSize() {
	if( $(window).width() < 1240 ) {
		$('body').addClass('narrow');
		createCookie('pagewidth','narrow', 30);
		arrangeWork('narrow');
	} else {
		$('body').removeClass('narrow');
		createCookie('pagewidth', 'wide', 30);
		arrangeWork('wide');
	}
}

window.onresize = checkWindowSize;

function createCookie(name,value,days,minutes) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	} else if( minutes ) {
		var date = new Date();
		date.setTime(date.getTime()+(minutes*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 followUsColors() {
    if (!$('#follow-us').length)
        return;
	$("#follow-us-fb").hover(
	  function () {
		$('#follow-us').css({'background-color' :'#3a5998', 'color' : '#7a8fba'});
		$('#follow-us-vimeo').css({'background-image' :'url(/wp-content/themes/luxus/img/follow-us-vimeo-blue.png)', 'color' : '#7a8fba'});
		$('#follow-us-twitter').css({'background-image' :'url(/wp-content/themes/luxus/img/follow-us-twitter-blue.png)', 'color' : '#7a8fba'});
	  }, 
  function () {
   		$('#follow-us').css({'background-color' :'#00acdc', 'color' : '#fff'});
		$('#follow-us-vimeo').css({'background-image' : 'url(/wp-content/themes/luxus/img/follow-us-vimeo.png)', 'color' : '#fff' });
		$('#follow-us-twitter').css({'background-image' : 'url(/wp-content/themes/luxus/img/follow-us-twitter.png)', 'color' : '#fff' });
  } );
    $("#follow-us-twitter").hover(
	  function () {
		$('#follow-us').css({'background-color' :'#67a72b', 'color' : '#98c470'});
		$('#follow-us-fb').css({'background-image' :'url(/wp-content/themes/luxus/img/follow-us-fb-green.png)', 'color' : '#98c470' });
		$('#follow-us-vimeo').css({'background-image' :'url(/wp-content/themes/luxus/img/follow-us-vimeo-green.png)', 'color' : '#98c470' });
	  }, 
  	  function () {
   		$('#follow-us').css({'background-color' :'#00acdc', 'color' : '#fff'});
		$('#follow-us-fb').css({'background-image' :'url(/wp-content/themes/luxus/img/follow-us-fb.png)', 'color' : '#fff' });
		$('#follow-us-vimeo').css({'background-image' :'url(/wp-content/themes/luxus/img/follow-us-vimeo.png)', 'color' : '#fff' });
  } );
	$("#follow-us-vimeo").hover(
	  function () {
		$('#follow-us').css({'background-color' :'#d83384', 'color' : '#e575ac'});
		$('#follow-us-fb').css({'background-image' :'url(/wp-content/themes/luxus/img/follow-us-fb-red.png)', 'color' : '#e575ac'});
		$('#follow-us-twitter').css({'background-image' :'url(/wp-content/themes/luxus/img/follow-us-twitter-red.png)', 'color' : '#e575ac'});
	  }, 
  function () {
   		$('#follow-us').css({'background-color' :'#00acdc', 'color' : '#fff'});
		$('#follow-us-fb').css({'background-image' : 'url(/wp-content/themes/luxus/img/follow-us-fb.png)', 'color' : '#fff' });
		$('#follow-us-twitter').css({'background-image' : 'url(/wp-content/themes/luxus/img/follow-us-twitter.png)', 'color' : '#fff' });
  } );
}

/* OUR WORK */

function initOurWork() {
	$(".work-case").each(
		function(i) {
			$(this).addClass('child-'+i);
		}
	);
	$(window).width() > 1240 ? arrangeWork('wide') : arrangeWork('narrow');
	if( $('body.home').length > 0 ) {
		$(".work-wrapper:eq(1)").addClass('second-row').find('.work-img').css({ height: '0px', width: '225px' });
		$(".work-wrapper").mouseenter(
			function() {
				$(this).find('.work-img').stop().animate({ height: '140px'}, { duration: 500, easing: 'easeOutCirc' });
				$(this).siblings('.work-wrapper').find('.work-img').stop().animate({ height: '0px' }, { duration: 500, easing: 'easeOutCirc' });
			}
		);
		$(".work-wrapper").click(
			function() {
				$(this).find('.work-img').stop().animate({ height: '140px'}, 500);
				$(this).siblings('.work-wrapper').find('.work-img').stop().animate({ height: '0px' }, 500);
			}
		);
	}
	
	$('.work-img').each(
		function() {
			var lnk = $(this).siblings('.work-descr').find('a').attr('href');
			$(this).append('<div class="curtain"></div>');
			$(this).find('.curtain').click( function() { location.href = lnk } );
		}
	);
	$('.curtain').css({ opacity: 0 });
	
	
	$(".work-case .work-img").hover(
		function() {
			$(this).find('.curtain').stop().animate({ opacity: .6 }, { duration: 500, easing: 'easeOutCirc' });
		},
		function() {
			$(this).find('.curtain').stop().animate({ opacity: 0 }, { duration: 500, easing: 'easeInCirc' });
		}
	);
	
}

function arrangeWork(type) {
	if( $("body.home").length > 0 ) {
		if( type == 'narrow' ) {
			$(".work-wrapper .child-4").hide();
			$(".work-wrapper .child-9").hide();
		} else {
			$(".work-wrapper .child-4").show();
			$(".work-wrapper .child-9").show();
		}
	}
}

function arrangeTweets() {
	$(".tweet").each( function(i) { $(this).addClass('child-'+i); } );
}

var users = new Array();

function relative_time(time_value) {
      var parsed_date = Date.parse(time_value);
      var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
      var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
      if(delta < 60) {
      return 'less than a minute ago';
      } else if(delta < 120) {
      return 'about a minute ago';
      } else if(delta < (45*60)) {
      return (parseInt(delta / 60)).toString() + ' minutes ago';
      } else if(delta < (90*60)) {
      return 'about an hour ago';
      } else if(delta < (24*60*60)) {
      return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
      } else if(delta < (48*60*60)) {
      return '1 day ago';
      } else {
      return (parseInt(delta / 86400)).toString() + ' days ago';
      }
    }

function initTweet() {
	if( !document.getElementById('tweets') ) return;
	var url = 'http://api.twitter.com/1/weareluxus/lists/ourtweets/statuses.json?per_page=200&callback=?';
	$.getJSON(url,
	function(json){
		$("#tweets").empty();
		$(json).each( function( i, item ) {
			addTweet(item);
		});
		arrangeTweets();
	});
}

var tweets = 0;
function addTweet(item) {
	if( !users[item.user.screen_name] ) {
		tweets++;
		if( tweets > 5 ) {
			return false;
		}
		users[item.user.screen_name] = true;
		var thedatestr = relative_time(item.created_at);
		var text = item.text.linkify(item.user.profile_text_color);
		text = text.linkifynames(item.user.profile_text_color);
		if ( item.text.length > 120 ) textSize = 9;
		else if ( item.text.length > 80 ) textSize = 13;
		else textSize = 15;
		var profile_image_url = item.user.profile_image_url;
		var profile_image = '<img src="'+profile_image_url+'" alt="" />';
		var link_color = '';
		var bg_color = ' style="background: #'+ item.user.profile_sidebar_fill_color + '; color: #'+item.user.profile_text_color+'"';
		var li_str = '<div class="tweet"><p style="font-size:'+textSize+'px">'+text+'</p><span>'+thedatestr+' ~ <a href="http://twitter.com/'+item.user.screen_name+'/"'+link_color+'>'+item.user.name+'</a> </span></div>';
		$("#tweets").append( li_str );
	}
}

function tagArchive() {
    $("#tagstuff a")
        .click(
            function() {
                $("#tagstuff a").removeClass('active');
                $(this).addClass('active');
                var tag = $(this).attr('rel');
                var c = $(".work-case").not('.'+tag).length;
                var j = 0;
                $(".work-case").not('.'+tag).fadeOut(200,
                    function() {
                        j++;
                        if( j == c )
                            $("."+tag).fadeIn(1000);
                    }
                );
                return false;
            }
        );
}

function showRightTag() {
    if( $('body.page-template-page-work-php').length == 0 || location.hash == '' ) {
        return;
    }
    $("#tagstuff a").removeClass('active');
    var tag = location.hash.replace('#', '');
    var c = $(".work-case").not('.'+tag).length;
    if( c == 0 ) {
        return;
    }
    var j = 0;
    $("#tagstuff a").each(
        function() {
            if( $(this).attr('rel') == tag ) {
                $(this).addClass('active');
            }
        }
    )
    $(".work-case").not('.'+tag).fadeOut(200,
        function() {
            j++;
            if( j == c )
                $("."+tag).fadeIn(1000);
        }
    );
}

/* FLASH SCRIPTS */

function getFlashMovie(movieName) {
	if (navigator.appName.indexOf("Microsoft") != -1) {
		return window[movieName];
	}
	else {
		return document[movieName];
	}
}

function changeVideo(url) {
	 getFlashMovie("videoplayer").changeVideo(url);
	 
}

function resetPlayer(id) {
	getFlashMovie("videoplayer").resetPlayer();
}

function videoPause() {
	$('.palkki').animate({ top: '0px' });
}

function videoPlay() {
	$('.palkki').animate({ top: '-200px' });
	
	if(mode == true){
		$('.big-picture').append('<div class="dark-layer"></div>');
		$('.dark-layer').fadeTo(1000, 0.9);
		mode = false;
	}
}

function videoReady() {
	videor = true;
	showVideo(videoUrl);
}

function videoEnd() {
	$('.dark-layer').remove();
	mode = true;
}

/* BIG PICTURE STUFF */
var videoUrl = '';
var videor = false;
function changeImage(id, first_el) {
    $('#flash-video-holder').css({left: '-999px'});
	if(getFlashMovie('videoplayer') && first_el != true) {
		resetPlayer();
	}
	$('.palkki').animate({ top: '0px' });
	var dv = $("div#"+id);
	var imgsrc = dv.find('img').attr('src');
	$(".big-picture").css({ 'background-image': 'url('+imgsrc+')' });
	
	if( dv.hasClass('video') ) {
		videoUrl = imgsrc;
		$('#flash-video-holder').css({left: '0px'});
		if(videor) {
		    showVideo(videoUrl);
		}
	}
}

var firstBP = true;
function prepareBigPicture() {
    if($('div.hide').length == 0) {
        return;
    }
    $('.hide').each(
    	function(i) {
    		var id = $(this).attr('id').replace('h','p');
    		$("#p-navi").append('<li id="'+id+'">'+(i+1)+'</li>');
    		if(firstBP) {
    			$("#"+id).addClass('active');
    			changeImage($(this).attr('id'), firstBP);
    			firstBP = false;
    		}
    	}
    );
    if( $('.hide').length == 1 ) {
        $("#p-navi").hide();
    }
    $("#p-navi li").click(
    	function() {
    		$("#p-navi li.active").removeClass('active');
    		$(this).addClass('active');
    		var id = $(this).attr('id').replace('p','h');
    		changeImage(id, false);
			
			$('.dark-layer').remove();
			mode = true;
    	}
    );
}

function showVideo(img) {
    var videourl = img.replace('.jpg', '.flv');
	var strIndex = videourl.lastIndexOf("/") + 1;
	var flvFile = videourl.substring(strIndex);
	
    if (accessFromSG) {
        changeVideo('http://www.luxusonlinesg.com/showreel/2010/06/' + flvFile);
	}
    else {
        changeVideo(videourl);
    }
}
