
$(document).ready(function() {
	
	// form submit control
	$("form").submit(function() {
		$(this).find("p.err").remove();
		var err = new Array();
		$(this).find(":input, :radio, :checkbox").each(function() {
			var v = validate_field($(this));
			if (!v.valid) {
				err.push(v.msg);
				$(this).addClass("invalid");
			} else {
				$(this).removeClass("invalid");
			}
		});
		if (err.length>0) {
			if ($(this).find("p.err").size()==0) $(this).prepend("<p class='err'></p>");
			$(this).find("p.err").html(err.join("<br/>"));
		}
		return (err.length>0)? false : true;
	});
	
	// website selector
	$("select#ortofon_websites").change(function() {
		if ($(this).attr("selectedIndex")!=0) {
			send_tracking_code("Outbound","Other sites",$(this).find("option:selected").val());
			window.open($(this).find("option:selected").val());
		}
	});
	
	// website selector
	$(".catch-us a").click(function() {
		send_tracking_code("Outbound","Catch us",$(this).attr("href"));
		window.open($(this).attr("href"));
		return false;
	});
	
	// input field label as value
	$("#newsletter-signup input#email").focus(function() {
		if ($(this).val()==$(this).attr("defaultValue")) $(this).val("");
	}).blur(function() {
		if ($(this).val()=="") $(this).val($(this).attr("defaultValue"));
	});
	
	// harmonica elements
	$("ul.harmonica").addClass("active").find("h2").click(function() {
		send_tracking_code("Harmonica",$(this).hasClass("active")?"Collapse":"Expand",$(this).html());
		$(this).toggleClass("active").parent().find(".details").slideToggle();
	}).hover(function() {
		$(this).addClass("hover");
	},function() {
		$(this).removeClass("hover");
	});
	
	// shared tech mindmap
	$("ul#shared-tech").addClass("active").find("li").mouseover(function(e) {
		e.stopImmediatePropagation();
		if ($("ul#shared-tech #details").size()<1) $("ul#shared-tech").append("<li id='details'>test</li>");
		var pos = $(this).position();
		$("ul#shared-tech #details").data("hColor",$(this).find("h2").css("color")).html($(this).html()).css("top",pos.top).css("left",pos.left).show().each(function() {
			var off = $(this).offset();
			var pOff = $(this).offsetParent().offset();
			if (off.left+$(this).outerWidth()+20>=$(window).width()) $(this).css("left",$(window).width()-pOff.left-$(this).outerWidth()-20);
			$(this).find("h2").css("color",$(this).data("hColor"));
		});
		
	});
	$("ul#shared-tech").mouseleave(function() {
		$(this).find("#details").remove();
	})

	// new win links
	$("a.newwin").each(function() {
		$(this).attr("target","_blank");
	})
	
	$("a[href*=www.youtube.com]").click(function() {
		var url = $(this).attr("href");
		var movie_id = url.match(/[\w-]{11,11}/gi).pop();
		var track = $(this).attr("title")||movie_id;
		show_video(movie_id,track);
		return false;
	});
	
	
	$('a[rel=lightbox]').lightBox();

	sifr_init();
	
});


$(window).load(function() {
	
	// carousel elements
	$("ul.carousel").each(function(i) {
        if ($(this).find("li").length>1) {
			$(this).wrap("<div class='carousel-wrapper'>").after("<div class='prev crs"+i+"prev'></div>","<div class='next crs"+i+"next'></div>").wrap("<div class='crs"+i+"'></div>");
			var h = 0;
			$(this).find("li").each(function() {
				h = Math.max(h,$(this).get(0).offsetHeight);
			});
			$(this).height(h).find("li").height(h);
			
			$("div.crs"+i).jCarouselLite({
                btnNext: ".crs"+i+"next",
                btnPrev: ".crs"+i+"prev",
                visible:1,
				scroll:1,
				afterEnd:function(a) {
					var label = ($(a).find("h2").size()!=0)? $(a).find("h2").html() : $(a).find("img").attr("alt");
					send_tracking_code("Carousel","Display",label);
				}
            });
        }
    });

	show_signup();
	if (window.location.hash!='') {
		var movie_id = null;
		try {
			movie_id = window.location.hash.match(/[\w-]{11,11}/gi).pop();
		} catch(e) {}
		if (movie_id) show_video(movie_id);
	}
});

function show_signup() {
	if (window.location.search.indexOf("clear=1")!=-1) eraseCookie("seen-popup");
	
	if (readCookie("seen-popup")!="1") { 
		
		createCookie("seen-popup","1",30);
	
		if ($("#overlay").size()==0) $("body").append("<div id='overlay'></div>");
		$("#overlay").css("width","100%").css("height",$(document).height());
	
		if ($("#newsletter-popup").size()==0) $("body").append("<div id='newsletter-popup'><div id='newsletter-close'></div></div><div id='newsletter-popup-bg'></div>");
		$("#newsletter-popup").append($("#newsletter-signup form").clone(true));
		$("#newsletter-popup button img").attr("src",$("#newsletter-popup button img").attr("src").replace(/signup_red.gif|signup.gif/,"signup_big.gif"));
	
		$("#overlay, #newsletter-close").click(function() {
			$("#overlay, #newsletter-popup, #newsletter-popup-bg").remove();
		});
	}
}

function show_video(movie_id,track) {
	send_tracking_code("Video","Open");
	
	if ($("#overlay").size()==0) {
		$("body").append("<div id='overlay'></div><div id='movie-popup'><div id='ytplayer'></div><div id='movie-close'></div></div>");
	}
	var embed_url = "http://www.youtube.com/v/"+movie_id+"&hl=en_US&fs=1&rel=0&autoplay=1&enablejsapi=1&playerapiid=ytplayer";
	
//	var str = '<object class="ytplayer" width="100%" height="100%"><param name="movie" value="'+embed_url+'"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed class="ytplayer" src="'+embed_url+'" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="100%" height="100%"></embed></object>';

	var params = { allowScriptAccess: "always" };
    var atts = { id: "myytplayer" };
    swfobject.embedSWF(embed_url,"ytplayer", "100%", "100%", "8", null, null, params, atts);
	
	
	$("#overlay").css("width","100%").css("height",$(document).height());
//	$("#movie-popup").append(str);
	$("#movie-close, #overlay").click(function() {
		send_tracking_code("Video","Close");
		$("#overlay, #movie-popup, #movie-close").remove();
	});
}


function onYouTubePlayerReady(playerId) {
	ytplayer = document.getElementById("myytplayer");
	ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
}

function onytplayerStateChange(newState) {
	/*
	if ($("#status").size()==0) {
		$("body").append("<div id='status' style='position:absolute; background:#fff; z-index:50; top:0px; left:0px; width:200px'>Ready</div>");
	}	
	var states = new Array();
	states["state-1"] = "unstarted";
	states["state0"]  = "ended";
	states["state1"]  = "playing";
	states["state2"]  = "paused";
	states["state3"]  = "buffering";
	states["state5"]  = "video cued";
	
	var str = "Player's new state: " + states["state"+newState];
	$("#status").append(str+"<br/>");
	*/
	if (newState==0) send_tracking_code("Video","Completed","DJ Fly");
}

var frutiger = {
	src: 'assets/sifr/flash/frutiger_extra_black_condensed.swf',
	ratios: [9, 1.16, 18, 1.08, 20, 1.03, 29, 1.02, 50, 1, 75, 0.99, 117, 0.98, 122, 0.97, 0.98]
};
sIFR.activate(frutiger);

function sifr_init() {

	sIFR.replace(frutiger, {
		selector: 'h1'
		,css: [
			'.sIFR-root {text-transform:uppercase}'
		]
		,wmode: 'transparent'
	});
}

function validate_field(o) {
	var v = {valid:false, msg:""};
	
	switch($(o).attr("id")) {
			
		case "fullname":
			v.valid = ($(o).val().match(pattern.fullname))? true:false;
			v.msg = "Please enter both your first and last name";
			break;
			
		case "dj_name":
			v.valid = ($(o).val()!="")? true:false;
			v.msg = "Please enter your DJ name";
			break;
		
		case "email":
			v.valid = ($(o).val().match(pattern.email))? true:false;
			v.msg = "Please enter a valid email address";
			break;
			
		case "country":
			v.valid = ($(o).attr("selectedIndex")!=0)? true:false;
			v.msg = "Please select your country of residence";
			break;
		
		case "dj_type":
			v.valid = ($(o).attr("selectedIndex")!=0)? true:false;
			v.msg = "Please select your DJ type";
			break;
	
		case "music_type":
			v.valid = ($(o).attr("selectedIndex")!=0)? true:false;
			v.msg = "Please select your music type";
			break;

		default:
			v.valid = true;
			break;
	}
	return v;
}


var pattern = {
	"email":			/^([\w\-\.]+)@((\[([0-9]{1,3}\.){3}[0-9]{1,3}\])|(([\w\-]+\.)+)([a-zA-Z]{2,4}))$/, // any email address
	"letters":			/^([a-zA-Z\u0080-\u00FF]+)$/, // only letters
	"lettersnumbers": 	/^([a-zA-Z\u0080-\u00FF0-9]+)$/, // will validate letters and/or numbers
	"lettersspace":		/^([a-zA-Z\u0080-\u00FF- ]+)$/, // only letters and spaces
	"numbers":			/^\d+$/, // only numbers
	"float":			/^\d+(,|\.)?(\d+)?$/, // only numbers
	"dkphone":			/^(\d{8})(.*)/,
	"dkzip":			/^(\d{3,4})$/, 
	"date": 			/^([0-2]?[1-9]|[3][0,1]{1})(\/(([1]{1}[0-2]|[0]?[1-9]))\/|\.(([1]{1}[0-2]|[0]?[1-9]))\.| (([1]{1}[0-2]|[0]?[1-9])) |-(([1]{1}[0-2]|[0]?[1-9]))-)(\d{4}|\d{2})$/, // DD[/. ]MM[/. ]YY(YY)
	"varchar":			/.+/, // At least one character
	"fullname":			/([a-zA-Z\u0080-\u00FF]{2,}) ([a-zA-Z\u0080-\u00FF]{2,})/ // First- and lastname
}

function send_tracking_code(category,action,label) {
	//alert("Category: "+category +'\nAction: '+ action +'\nLabel: '+ label);
	pageTracker._trackEvent(category, action, label);
}

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);
}