/*
CSS Browser Selector v0.3.3 (Sep 09, 2009)
Rafael Lima (http://rafael.adm.br)
http://rafael.adm.br/css_browser_selector
License: http://creativecommons.org/licenses/by/2.5/
Contributors: http://rafael.adm.br/css_browser_selector#contributors
*/
function css_browser_selector(u){var ua = u.toLowerCase(),is=function(t){return ua.indexOf(t)>-1;},g='gecko',w='webkit',s='safari',h=document.getElementsByTagName('html')[0],b=[(!(/opera|webtv/i.test(ua))&&/msie\s(\d)/.test(ua))?('ie ie'+RegExp.$1):is('firefox/2')?g+' ff2':is('firefox/3.5')?g+' ff3 ff3_5':is('firefox/3')?g+' ff3':is('gecko/')?g:/opera(\s|\/)(\d+)/.test(ua)?'opera opera'+RegExp.$2:is('konqueror')?'konqueror':is('chrome')?w+' chrome':is('iron')?w+' iron':is('applewebkit/')?w+' '+s+(/version\/(\d+)/.test(ua)?' '+s+RegExp.$1:''):is('mozilla/')?g:'',is('j2me')?'mobile':is('iphone')?'iphone':is('ipod')?'ipod':is('mac')?'mac':is('darwin')?'mac':is('webtv')?'webtv':is('win')?'win':is('freebsd')?'freebsd':(is('x11')||is('linux'))?'linux':'','js']; c = b.join(' '); h.className += ' '+c; return c;}; css_browser_selector(navigator.userAgent);

/*
 * doTimeout - v0.4 - 7/15/2009
 * http://benalman.com/projects/jquery-dotimeout-plugin/
 * 
 * Copyright (c) 2009 "Cowboy" Ben Alman
 * Licensed under the MIT license
 * http://benalman.com/about/license/
 */
(function($){var a={},c="doTimeout",d=Array.prototype.slice;$[c]=function(){return b.apply(window,[0].concat(d.call(arguments)))};$.fn[c]=function(){var e=d.call(arguments),f=b.apply(this,[c+e[0]].concat(e));return typeof e[0]==="number"||typeof e[1]==="number"?this:f};function b(l){var m=this,h,k={},n=arguments,i=4,g=n[1],j=n[2],o=n[3];if(typeof g!=="string"){i--;g=l=0;j=n[1];o=n[2]}if(l){h=m.eq(0);h.data(l,k=h.data(l)||{})}else{if(g){k=a[g]||(a[g]={})}}k.id&&clearTimeout(k.id);delete k.id;function f(){if(l){h.removeData(l)}else{if(g){delete a[g]}}}function e(){k.id=setTimeout(function(){k.fn()},j)}if(o){k.fn=function(p){o.apply(m,d.call(n,i))&&!p?e():f()};e()}else{if(k.fn){j===undefined?f():k.fn(j===false);return true}else{f()}}}})(jQuery);

/*
jQuery SWFObject Plugin v1.0.9
http://jquery.thewikies.com/swfobject/
*/
(function(F,C){var D=function(H){var G,I=[];for(G in H){if(/string|number/.test(typeof H[G])&&H[G]!==""){I.push(G+'="'+H[G]+'"')}}return I[A]("")},E=function(I){var G,K,J=[],H;if(typeof I=="object"){for(G in I){if(typeof I[G]=="object"){H=[];for(K in I[G]){H.push([K,"=",encodeURIComponent(I[G][K])][A](""))}I[G]=H[A]("&amp;")}if(I[G]){J.push(['<param name="',G,'" value="',I[G],'" />'][A](""))}}I=J[A]("")}return I},B=false,A="join";F[C]=(function(){try{var G="0,0,0",H=navigator.plugins["Shockwave Flash"]||ActiveXObject;G=H.description||(function(){try{return(new H("ShockwaveFlash.ShockwaveFlash")).GetVariable("$version")}catch(J){}}())}catch(I){}G=G.match(/^[A-Za-z\s]*?(\d+)[\.|,](\d+)(?:\s+[d|r]|,)(\d+)/);return{available:G[1]>0,activeX:H&&!H.name,version:{major:G[1]*1,minor:G[2]*1,release:G[3]*1},hasVersion:function(K){var N=this.version,L="major",M="minor",J="release";K=(/string|number/.test(typeof K))?K.toString().split("."):K||[0,0,0];K=[K[L]||K[0]||N[L],K[M]||K[1]||N[M],K[J]||K[2]||N[J]];return(K[0]<N[L])||(K[0]==N[L]&&K[1]<N[M])||(K[0]==N[L]&&K[1]==N[M]&&K[2]<=N[J])},expressInstall:"expressInstall.swf",create:function(J){if(!F[C].available||B||!typeof J=="object"||!J.swf){return false}if(J.hasVersion&&!F[C].hasVersion(J.hasVersion)){J={swf:J.expressInstall||F[C].expressInstall,attrs:{id:J.id||"SWFObjectExprInst",name:J.name,height:Math.max(J.height||137),width:Math.max(J.width||214)},params:{flashvars:{MMredirectURL:location.href,MMplayerType:(F[C].activeX)?"ActiveX":"PlugIn",MMdoctitle:document.title.slice(0,47)+" - Flash Player Installation"}}};B=true}else{J=F.extend(true,{attrs:{id:J.id,name:J.name,height:J.height||180,width:J.width||320},params:{wmode:J.wmode||"opaque",flashvars:J.flashvars}},J)}if(F[C].activeX){J.attrs.classid=J.attrs.classid||"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000";J.params.movie=J.params.movie||J.swf}else{J.attrs.type=J.attrs.classid||"application/x-shockwave-flash";J.attrs.data=J.attrs.data||J.swf}return["<object ",D(J.attrs),">",E(J.params),"</object>"][A]("")}}}());F.fn[C]=function(G){if(typeof G=="object"){this.each(function(){var I=document.createElement(C);var H=F[C].create(G);if(H){I.innerHTML=H;if(I.childNodes[0]){this.appendChild(I.childNodes[0])}}})}else{if(typeof G=="function"){this.find("object").andSelf().filter("object").each(function(){var I=this,H="jsInteractionTimeoutMs";I[H]=I[H]||0;if(I[H]<660){if(I.clientWidth||I.clientHeight){G.call(this)}else{setTimeout(function(){F(I)[C](G)},I[H]+66)}}})}}return this}}(jQuery,"flash"));


var root_url = "http://www.musex.fi/";

// Replaces text with replacement in string
function replace(str,text,replacement) {
	
    var strLength = replacement.length, txtLength = text.length;
    if ((strLength == 0) || (txtLength == 0)) return str;
    
    var i = str.indexOf(text);
    if ((!i) && (text != str.substring(0,txtLength))) return str;
    if (i == -1) return str;
    var newstr = str.substring(0,i) + replacement;
    if (i+txtLength < strLength)
        newstr += replace(str.substring(i+txtLength,strLength),text,replacement);
    
    return newstr;
}


$(document).ready(function() {
	
	// font replacement
	Cufon.replace($("h1, p.cufon, p.cufon2, body.en h2, body.fi h2, body.jp #sidebar h2, h3.cufon, h4.cufon"), { fontFamily: 'Avenir', hover: true });
	Cufon.replace($("h3.cufon a"), { fontFamily: 'Avenir', hover: true });

	$(".tab-closed").click(function(e){
		e.preventDefault();

		var link = $(this),
			infoDiv = link.parents().eq(1).next(".info");

		if(infoDiv.is(":visible")) {
			link.removeClass("tab-open");
			infoDiv.slideUp(1); 
		} else {
			link.addClass("tab-open");
			infoDiv.slideDown(1); 
		}

	});
	
	// rounded images
	$("body#news #content div.text img, body#about #content div#toggle-staff img, body.jp div.text img").each(function() {
	//$("body#news #content div.text img, body#about #content div#toggle-staff img, body#event #content div.desc img").each(function() {
	//$("#content div.text img").each(function() {
		
		var im = $(this).attr("src").split(root_url);
		if(im[1] == undefined) var im = $(this).attr("src").split("http://musexfi.virtualserver21.nebula.fi/");
		var img = im[1];
		var im_position = "T";
		if($(this).hasClass("right")) { var alignment = "right"; } else { var alignment = "left";	}
		if($(this).attr("title").length > 0) {
			im_position = $(this).attr("title");
			$(this).attr("title", $(this).attr("alt"));
		}
		
		$(this).hide().attr("width", "140").attr("style", "").attr("height", "140").attr("src", root_url + "images/thumb/phpThumb.php?src=/" + img + "&w=140&h=140&zc=" + im_position + "&fltr[]=mask|/images/thumb/mask140.png&f=png").addClass("png").addClass(alignment).show();
	});
	$("body.article div.text img").attr("style","").addClass("right"); // news articles
	
	// anti-spam email
	$('.email').each(function()
	{
	    var obfAddress = $(this).text();
	    var realAddress = obfAddress.replace(/\[at\]/g, '@').replace(/\[dot\]/g, '.');
	    var emailLink = document.createElement('a');
	    $(emailLink).attr(
	    {
	        'href': 'mailto:' + realAddress,
	        'title': 'Email: ' + realAddress,
	        'class': 'email-address'
	    }).text(realAddress);
	    $(this).replaceWith(emailLink);
	});
	
	// input clearing on focus
    $.fn.clearInputText = function() {
		return this.focus(function() {
			if( this.value == this.defaultValue) {
				this.value = "";
			}
		}).blur(function() {
			if(!this.value.length) {
				this.value = this.defaultValue;
			}
		});
	};
	$("input#username").submit(function() {
		if ($("input#username").val() == "Username" || $("input#username").val() == "") {
		   	return false;
		} 
	});
	
	// replace input=text with input type=password
	$("input#password").focus(function() {
		$(this).remove();
		$("div#header div.password").html('<input class="text" id="password" name="password" type="password" value="" tabindex="2" />');
		$("div#header input#password").focus();
		//$(this).focus();
		return false;
	});
	$("input#username").clearInputText();
	$("input#password").clearInputText();
	
	
	// easing for animation
	$.easing.custom = function (x, t, b, c, d) 
	{ 
	    // easeInOutQuint from http://gsgd.co.uk/sandbox/jquery/easing/jquery.easing.1.3.js
		if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
		return c/2*((t-=2)*t*t*t*t + 2) + b;
	}
	
	// create global var namespace
	$.glob = { 
		anchorscroll: true 
	}
	
	// jQuery SmoothScroll | Version 09-11-02
	// from http://blog.medianotions.de/en/articles/2009/smoothscroll-for-jquery

	$('a[href*=#]').click(function() {
	// duration in ms
	var duration=700;
	
	// easing values: swing | linear
	var easing='swing';
	
	// get / set parameters
	var newHash=this.hash;
	var target=$(this.hash).offset().top;
	var oldLocation=window.location.href.replace(window.location.hash, '');
	var newLocation=this;
	
	// make sure it's the same location      
	if(oldLocation+newHash==newLocation)
	{
	  // animate to target and set the hash to the window.location after the animation
	  if(newHash == '#top') {
	  	  $('html:not(:animated),body:not(:animated)').animate({ scrollTop: target }, duration, "custom", function() {
	       // add new hash to the browser location
	       window.location.href=newLocation;
	  	  });
	  } else {
	      $.doTimeout(300, function(){ // wait a second
	
	    	if($.glob.anchorscroll == true) {
	    		$("html:not(:animated),body:not(:animated)").animate({ scrollTop: target+8 }, 1500, "custom", function() {
	    		 /*location.hash=hash;*/ 
	    		});
	    		$.doTimeout(2000, function(){
	    			window.location.href=newLocation;
	    		});
	    	}
		  });
	  }
	
	  // cancel default click action
	  return false;
	}
	});
	
	// link back
	$('a.back').click(function() {
		history.back();
		return false;
	});
	
	// toggler
	$("a.toggler").addClass('toggler-off');
	$("div.togglediv").addClass('hide');
	$.fn.toggler = function(div) {
		
		$(div).slideToggle(90);
		
    	if($(this).is('.toggler-on') ) {
          $(this).removeClass('toggler-on').addClass('toggler-off');
          $.glob.anchorscroll = false;
        } else {
          $(this).removeClass('toggler-off').addClass('toggler-on');
          //$.glob.anchorscroll = true; 
          $.glob.anchorscroll = false;
        }
        return false;
	};
	
	if($('a.top'.length)) {
    	if($("html").hasClass("ie")) {
    		// hide top links from IE
    	} else {
    		$('a.top').fadeIn('slow');
    	}
    }
	
	// see if an anchor link is opened
	if(window.location.hash) {
		var winHash = window.location.hash.substr(1);
		if($('div#toggle-'+winHash).length) {
			//console.log(winHash+' exists, therefore is');
			$('div#toggle-'+winHash).slideToggle(90);
			$('a#'+winHash).removeClass('toggler-off').addClass('toggler-on');
            $.glob.anchorscroll = true;
            if($('a.top'.length)) $('a.top').fadeIn('slow');
		}
	}
	
	// toggles on page load
	if($('body#event div#toggle-artists'.length)) $('a#artists').toggler('#toggle-artists');
	
	// submit on select change
	
    $('body#events select#country').change(function () {
		$("form#search_country").submit();
	});
	
	
	// inline list menu
	$('dl.inline-list dd a').click(function() {
		$("dl.inline-list dd").removeClass('active');
		$(this).parent().addClass('active');
		return false;
	});
	
	//
    // ajax loading
	//
	
	var ajax_load = "<img src='images/layout/ajax-loader.gif' alt='Loading...' style='margin: 12px 0 3px 16px' />";  
	
    $("body#events dl#upcoming-menu dd a").click(function(){  
		
		$("#upcoming-list").hide();
		var ajaxUrl = $(this).attr('href');
        $("#upcoming-list").html(ajax_load).load($(this).attr('href') + " #upcoming-list");
        $("#upcoming-list").fadeIn();
        
    	return false;
    });
    
    $("body#events dl#past-menu dd a").click(function(){  
		
		$("#past-list").hide();
		var ajaxUrl = $(this).attr('href');
        $("#past-list").html(ajax_load).load($(this).attr('href') + " #past-list");
        $("#past-list").fadeIn();
        $("#past-list-year").hide();
    	return false;
    });

	
	// form validation
	
	if($("body").hasClass("fi")) {
		var errorMessage = 'Ole hyvä ja täytä kaikki vaaditut kentät.'; 
	} else {
		var errorMessage = 'Please, fill in all required fields.';
	}
		
	$("body#about form#contact").submit(function() {
		
		if ($("form#contact #Name").val() == "" || $("form#contact #Email").val() == "" || $("form#contact #Message").val() == "") {
		   	$('form#contact .error').html(errorMessage).fadeIn();
		   	return false;
		}
		
		$('input[type=submit]', this).attr('disabled', 'disabled');
		pageTracker._trackPageview('/contact/' + $("html").attr("lang"));
	});
	
	$("body#news form#newsletter").submit(function() {
		
		if ($("input#FirstName").val() == "" || $("input#LastName").val() == "" || $("input[name='cm-drtydt-drtydt']").val() == "" || $("input#StreetAddress").val() == "" || $("input#PostalCode").val() == "" || $("input#City").val() == "" || $("input[name='cm-f-jltkm']").val() == "") {
		   	$('form#newsletter .error').html(errorMessage).fadeIn();
		   	return false;
		}
		$('input[type=submit]', this).attr('disabled', 'disabled');
	});
	
	$("form#register_member_form input#company").addClass("quiet");
	$("form#register_member_form input#company").focus(function() {
		$(this).removeClass("quiet");
	});
	$("form#register_member_form input#company").clearInputText();
	$("form#register_member_form input#vat").addClass("quiet");
	$("form#register_member_form input#vat").focus(function() {
		$(this).removeClass("quiet");
	});
	$("form#register_member_form input#vat").clearInputText();
	
	$("form#register_member_form").submit(function() {
		
		// create screen & usernames
		var screenname = $("input[name='firstname']").val() + " " + $("input[name='surname']").val();
		if(screenname > 22) {
   			screenname = screenname.substring(0,22);
		}
		$("input[name='screen_name']").attr("value", screenname);
		$("input[name='username']").attr("value", $("input[name='email']").val());
		$("input[name='email_confirm']").attr("value", $("input[name='email']").val());
		
		var newline;
		if (document.all) newline = '\r\n';
		else newline = '\n';

		var str_industry = '';
		$('select#industry > option:selected').each(function() {
    		str_industry += "" + $(this).val() + newline;
		});
		$("input[name='m_field_id_16']").attr("value", str_industry);
		
		var str_media = '';
		$('select#media > option:selected').each(function() {
    		str_media += "" + $(this).val() + newline;
		});
		$("input[name='m_field_id_15']").attr("value", str_media);
		
		var str_genre = '';
		$('select#genre > option:selected').each(function() {
    		str_genre += "" + $(this).val() + newline;
		});
		$("input[name='m_field_id_17']").attr("value", str_genre);
		
		var str_orgs = '';
		$('select#member_orgs > option:selected').each(function() {
    		str_orgs += "" + $(this).val() + newline;
		});
		$("input[name='m_field_id_18']").attr("value", str_orgs);
		
		if ($("input[name='firstname']").val() == "" || $("input[name='surname']").val() == "" || $("input[name='email']").val() == "" || $("select[name='location']").val() == "" || $("input[name='password']").val() == "" || $("input[name='password_confirm']").val() == "") {
		   	$('div.error').html(errorMessage).fadeIn();
		   	return false;
		}
		
		$('input[type=submit]', this).attr('disabled', 'disabled');
		pageTracker._trackPageview('/registered/' + $("html").attr("lang"));
	});
	
	// slideshow pro
	
	if($("body#event #ssp #xmlfile a").length) {
		var ssp_xml = $("body#event #ssp #xmlfile a").attr('href');
	} else {
		var ssp_xml = $("body#event #ssp #xmlfile").html();
	}
	var ssp_url = 'xmlfile=' + ssp_xml + '&#38;xmlfiletype=Director';
	
	
	$("body#event #ssp").empty().flash({
		
		swf: 'http://www.musex.fi/images/swf/event-photos.swf',
		flashvars: {},
		params: {
			FlashVars: ssp_url,
			menu: 'false'
		},
		attributes: {},     	
		width: '540',
		height: '360'
	});
	
	
	//$("body#event #ssp").empty().html('<iframe src="http://www.musex.fi/templates/ssp_frame.php?xml=' + ssp_xml + '" id="player" name="player" frameborder="0" width="540" height="360" marginheight="0" marginwidth="0" scrolling="no"></iframe>');
	

	// position footer to the bottom on short pages
	function fixFooter() { 
		
		var used_height = $("div#header").height() + $("div.footer-wrap").height();
		var min_height = 400 + used_height;
		
		if($(window).height() > min_height) {
			var avail_height = $(window).height() - used_height;
			var target_height = avail_height - 5;
			$("div.content-wrap").attr("style", "min-height: " + target_height + "px");
		} else {
			$("div.content-wrap").attr("style", "min-height: 400px");
		}
	}
	var resizeTimer = null;
	$(window).bind('resize', function() {
	   if (resizeTimer) clearTimeout(resizeTimer);
	   resizeTimer = setTimeout(fixFooter, 100);
	});
	fixFooter();
	
	// edit links
	if($("div.global-edit a").length) $("div.global-edit").addClass("global-edit-admin");
	
});
