/**
 * jQuery.browser.mobile (http://detectmobilebrowser.com/)
 *
 * jQuery.browser.mobile will be true if the browser is a mobile device
 *
 **/
(function(a){jQuery.browser.mobile=/android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))})(navigator.userAgent||navigator.vendor||window.opera);


jQuery.cookie = function (key, value, options) {
    
    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }
        
        value = String(value);
        
        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};


var ap_instances = new Array();

function ap_stopAll(playerID) {
	for(var i = 0;i<ap_instances.length;i++) {
		try {
			if(ap_instances[i] != playerID) document.getElementById("audioplayer" + ap_instances[i].toString()).SetVariable("closePlayer", 1);
			else document.getElementById("audioplayer" + ap_instances[i].toString()).SetVariable("closePlayer", 0);
		} catch( errorObject ) {
			// stop any errors
		}
	}
}

function ap_registerPlayers() {
	var objectID;
	var objectTags = document.getElementsByTagName("object");
	for(var i=0;i<objectTags.length;i++) {
		objectID = objectTags[i].id;
		if(objectID.indexOf("audioplayer") == 0) {
			ap_instances[i] = objectID.substring(11, objectID.length);
		}
	}
}

//var ap_clearID = setInterval( ap_registerPlayers, 100 );

 var requiredVersion = "9.0.0";
      var flashvars = {};
      var params = {
        scale: "noscale",
        salign: "tl",
        menu: "true",
        allowscriptaccess: "always",
        allownetworking: "all",
        wmode:"opaque",
        bgcolor: "#000000"
      };
      var attributes = {
        id: "homepageVideo",
        name: "homepageVideo"
      };

var a = 0;
var b = 0;
var timer;
var pictures = [];
var cache = [];
var initLoad = true;
var mobile = false;
var blocker = false;
(function ($) {
	var cache = [];
	// Arguments are image paths relative to the current page.
	$.preLoadImages = function () {
		var args_len = arguments.length;
		for (var i = args_len; i--;) {
			var cacheImage = document.createElement('img');
			cacheImage.src = arguments[i];
			cache.push(cacheImage);
		}
	}
})(jQuery)
jQuery.fn.blindToggle = function (speed, easing, callback) {
	var h = this.height() + parseInt(this.css('paddingTop')) + parseInt(this.css('paddingBottom'));
	return this.animate({
		marginTop: parseInt(this.css('marginTop')) < 0 ? 0 : -h
	}, speed, easing, callback);
}; /***** GALLERY PAGE ****/
/*
function showSmallImage(index) {
		index = index*1;
		$("ul.smallGallery").find("a").css("opacity", 0.4);
		$("#smallGalleryPic").attr("src", $(pictures[index]).attr("href"))
		$(pictures[index]).css("opacity", 1);
		
		b = index;
}*/

function isMobile() {
	var deviceAgent = navigator.userAgent.toLowerCase();
	var agentID = deviceAgent.match(/(iphone|ipod|ipad|android|blackberry|blazer|fennec)/);
	if (agentID) {
		mobile = true;
	}
} /****** GENERAL PAGE ***/

function globalSetup() {

    if (jQuery.browser.mobile) {
    		
         $("body").addClass("mobileMode");
    
    }
    
    
    
    jQuery.preLoadImages("imgs/foldout.png", "imgs/icons/danceunselected.png", "imgs/icons/circusselected.png", "imgs/icons/comedyselected.png", "imgs/icons/corporateselected.png", "imgs/icons/corporateunselected.png", "imgs/icons/danceselected.png", "imgs/icons/hotelresidencyselected.png", "imgs/icons/hotelresidencyunselected.png", "imgs/icons/magicselected.png", "imgs/icons/moreunselected.png", "imgs/icons/musicselected.png", "imgs/icons/privateselected.png", "imgs/icons/privateunselected.png", "imgs/icons/productlaunchselected.png", "imgs/icons/productlaunchunselected.png", "imgs/icons/speakerselected.png", "imgs/icons/weddingselected.png", "imgs/icons/weddingunselected.png", "imgs/foldouttab-over.png");
	$("p").each(function () {
		if ($(this).html() == "&nbsp;" || $(this).html() == "") {
			$(this).remove();
		}
	});
	isMobile();
	
   	
   	
   	$("ul.videos a").each(function() {
   	
   	
   		var url = $(this).attr('href');
   		var link = $(this);
   		var segs = url.split('/')
   	
   		$.embedly('http://www.youtube.com/watch?v='+segs[segs.length-1], {key: '9dcca450ad7f11e0b28a4040d3dc5c07'}, function(oembed, dict){
		   link.attr('title',oembed.title).css({overflow:'hidden', position:'relative'}).append( "<img style='position:absolute;width:15px; top:12px; left:25px;' src='/imgs/icons/videosmall.png'><img src='"+oembed.thumbnail_url+"' />" );
		});
   	
   	
   	
   	
   	});
   	
   	/*.embedly({key: '9dcca450ad7f11e0b28a4040d3dc5c07'}, function(oembed, dict){
	    
	    
	    if ( oembed == null)
	      return;
	    var output = "<img src='"+oembed.thumbnail_url+"' />";
	    
	    
	    
			$(dict["node"]).attr('title',oembed.title)
 	});*/
   	
   	Shadowbox.init();
   	
	if ($("div.blogPosts").size() > 0) {
	
		//alert($('div.embedly').find('a').size())
		//$('a').embedly()	
		
		
		$('div.embedly').find('a.noembed').each(function() {
		
		
			//alert($(this).attr('href'));		
		})
		
		
		$('div.embedly').find('a.embed').embedly({
			maxWidth: 605,
			maxHeight: 410, key: '9dcca450ad7f11e0b28a4040d3dc5c07'
		});
	} else {
		$('div.embedly').embedly({
			maxWidth: 450,
			maxHeight: 305, key: '9dcca450ad7f11e0b28a4040d3dc5c07'
		});
	}
	
	$("a.media-asset[href$=.mp3]").each(function() {
			var flashVarsM = {};
			flashVarsM.playerID=1;
			flashVarsM.bg= '0x333333'            // Background color
      flashVarsM.text = '0xFFFFFF';       // Text color
      flashVarsM.leftbg = '0x333333';        // Left background color
      flashVarsM.lefticon = '0x3AB8EF';      // Left icon color
      flashVarsM.rightbg = '0x4F4E4E';     // Right background color
      flashVarsM.rightbghover = '0x75797C';  // Right background hover color
      flashVarsM.righticon = '0xffffff';    // Right icon color
      flashVarsM.righticonhover = '0x3AB8EF';// Right icon hover color
      flashVarsM.slider = '0x666666';     // Progress slider color
      flashVarsM.track = '0x333333',         // Progress track color
      flashVarsM.loader = '0x3AB8EF',        // Loader bar color
      flashVarsM.border = '0x75797C',        // Border color
      flashVarsM.loop = "no";
      flashVarsM.autostart ='no';
	  flashVarsM.soundFile=$(this).attr("href");
			
	  var attributesM = {
        id: "audioPlayer",
        name: "audioPlayer"
      };
			 swfobject.embedSWF("swf/mp3player.swf", "mediaPlayer", "450", "24", requiredVersion, null, flashVarsM, params, attributesM);
	})
	
	
}

function aboutSetup() {

	if ($("#peopleContainer").size() > 0) {
		var current = 0;
		var peopleCount = $("#peopleList").find("li").size() ;
		$("div span:first-child")
		$("ul.peopleGroup").find("a:first-child").filter(":first").addClass("current");
		var people = $("#peopleList").find("a.personLink");
		people.click(function () {
			people.removeClass("current");
			$("div.personPanel").hide();
			$($(this).attr("href")).fadeIn();
			$($(this).attr("href")).find("div.wide").css("top", "-330px").animate({
				top: "0px"
			}, 750);
			return false;
		})
		$("#peopleList").find("a.left").click(function () {
			current -= 6;
			$("#peopleList").find("a.right").show();
			if (current < 1) {
				current = 0;
				$("#peopleList").find("a.left").hide();
			} else {
				$("#peopleList").find("a.left").show();
			}
			var pos = (current * 153) + 'px'
			if (current > 0) {
				pos = '-' + pos;
			}
			$("#peopleList").find("ul").stop(true, true).animate({
				left: pos
			}, 1000);
			return false;
		}).hide();
		$("#peopleList").find("a.right").click(function () {
			current += 6;
			$("#peopleList").find("a.left").show();
			if (current + 6 >= peopleCount) {
				$("#peopleList").find("a.right").hide();
				current = peopleCount - 6;
			} else {
				$("#peopleList").find("a.right").show();
			}
			$("#peopleList").find("ul").stop(true, true).animate({
				left: '-' + (current * 153) + 'px'
			}, 1000);
			return false;
		});
	}

}

function menuSetup() {
   var drops = $('li.dropdown');
   if (!jQuery.browser.mobile) {

   
   	    drops.hover(function () {
		     $(this).find('a.main').addClass('current');
		     $(this).find('ul').stop(true, true).slideDown();
	    }, function () {
		     $(this).find('a.main').removeClass('current');
		     $(this).find('ul').stop(true, true).slideUp();
	     });
   
   
   }
   
   drops.find('a.main').click(function () {
		if ($(this).hasClass('current')) {
			$(this).removeClass('current')
			$(this).parent().find('ul').stop(true, true).slideUp();
		} else {
			$(this).addClass('current')
			$(this).parent().find('ul').stop(true, true).slideDown();
		}
		return false;
	});


}

function tabsSetup() {

	$('#findGenre').change(function () {
		var val = $(this).val();
		if (val !== '') {
			$.ajax({
				type: "POST",
				url: "?s=genrelist",
				data: "genre=" + val,
				success: function (msg) {
					$('#findEventType').html(msg);
				}
			});
		}
	});

	$('#finderTabs').find('a.finderLink').toggle(function () {
		//$(this).parent().css('z-index','1').find('div.hidder').stop(true, true).slideDown('slow');
		$(this).parent().css('z-index', '1').addClass("currentTab").find('div.hidder').show();
		var el = $(this).parent().css('z-index', '1').find('div.hidder');
		el.css("margin-top", "-" + el.height() + "px");
		el.stop(true, true).animate({
			marginTop: "0px"
		}, "slow", 'swing');
		return false;
	}, function () {
		///$(this).parent().find('div.hidder').stop(true, true).slideUp('slow',function() { $(this).parent().css('z-index','0') });
		var el = $(this).parent().css('z-index', '1').removeClass("currentTab").find('div.hidder');
		el.stop(true, true).animate({
			marginTop: "-" + el.height() + "px"
		}, "slow", 'swing', function () {
			$(this).hide().parent().css('z-index', '0')
		});
		return false;
	});
	
	if ($('#findKeyword').val()=='') {
		$('#findKeyword').val('keyword, e.g. harp (optional)').focus(function(){
			$('#findKeyword').val('');
		});
	}
}

function blogSetup() {
	$("div.blogPosts").find("img").each(function () {
		var alt = $(this).attr("alt");
		if (alt !== "") {
			
			//var w = 605;
			
			//if ($(this).attr('width') !== 'undefined' ) {
			
			//    w = $(this).attr('width');
			//}
			
			$(this).removeAttr("height").removeAttr("width").wrap("<span class='post-image'></span>").parent().append("<br /><span class='caption'>" + alt + "</span>").nextUntil(':not(br)').remove();;
			
			//if (w<605) $(this).parent().css('width',w+"px");
			
			//$('img[src$=heading_shoppingcart.gif]').parent().nextUntil(':not(br)').remove();

		}
	})
	
	var testimonials = $("div.testimonials");
	
	if (testimonials.size()>0) {
	
	   if (testimonials.height()>210) {
	        testimonials.css({overflow:'hidden', height:'170px'}).after('<a href="#" class="testimonialsMore" style="padding-top:5px;display:block;">More</a>');
	        
	        testimonials.parent().find('a.testimonialsMore').click(function() {
	        		$(this).remove();
	        		testimonials.css({overflow:'show', height:'auto'});
	                return false;
	        });
	        
	   
	   
	   }
	
	}
	
	
	
}

function setupPage() {
	//$(document).pngFix();
	globalSetup();
	
	aboutSetup();
	
	
	
	
	blogSetup();
	
	
	menuSetup();
	
	tabsSetup()
}

function removeFlashVideo() {
	$("#videoWrapper").remove();
	$("#feed").show();
	$("#finderTabs").show();
	$('#imgWrapper').css('display','block').animate({opacity: 1}, 1500);
	$('#contentSpace').css('display','block').animate({opacity: 1}, 1500);
	$("#skipVideo").remove();
	
	 $("body").unbind('click');
	homepageAutoRotate();
}

function homepageSetup() {
	
	
	if ($('#tabMenu').size()>0) {
	   
	     
	  /*  if (!jQuery.browser.mobile && $.cookie('videoplayed')!=='true') {
              $.cookie('videoplayed', 'true', { expires: 7, path: '/' });
              $("#videoWrapper").show();
              swfobject.embedSWF("swf/VideoMain.swf", "flashVideoContainer", "100%", "100%", requiredVersion, null, flashvars, params, attributes);
			  $('#imgWrapper').hide().css('opacity',0);
			  
              $("#skipVideo").show();
			  $('#contentSpace').hide().css('opacity',0);
              $("#feed").hide();
              $("#finderTabs").hide();
              
              
              $("body").click(function () {
				removeFlashVideo();
				
		
				
			   });
              
          } else {
    
              homepageAutoRotate();
         }*/
           homepageAutoRotate();
	} 
	

	
	
	$('#tabMenu').find('a').click(function () {
	
		clearTimeout(timer);
	   
		$('#tabMenu').find('a').removeClass('current');
		$(this).addClass('current');
		$('#homeCarousel').find('div.tabwrapper').stop(true, true).hide();
		var slidshowid = $(this).attr('href') + '_imgs';
		$($(this).attr('href')).show();
		if (slidshowid == '#genreTab_imgs') {
			$('#imgContainer').stop(true, true).animate({
				top: '0'
			}, 1500);
		} else {
			$('#imgContainer').stop(true, true).animate({
				top: '-100%'
			}, 1500);
		}
		$('div.tabContent').hide();
		$($(this).attr('href')).find('li.current').each(function () {
			$($(this).find('a').attr('href')).show();
		});
		return false;
	});
	$('div.menuContentTab').find('a').click(function () {
	     clearTimeout(timer);
	   
	 
	     
	     if (!blocker) {
		
		$(this).parent().parent().find('li').removeClass('current');
		$(this).parent().addClass('current');
		$('div.tabContent').hide();
		$($(this).attr('href')).show();
		showBackground($(this).attr('href') + '_img');
	    }	
		return false;
	}).hover(function () {
		var cur = $(this).parent().parent().find("li.current");
		cur.addClass("override");
	}, function () {
		var cur = $(this).parent().parent().find("li.current");
		cur.removeClass("override");
	});
	var slider;
	$('div.imgSlider').each(function () {
		slider = $(this);
		$(this).find("img").each(function (i) {
			//$(this).attr("fixedwidth", $(this).width()).attr("fixedheight", $(this).height());
			$(this).attr("index",i);
			if (i==0) {
				slider.attr("current",$(this).attr("id")).attr("index",0);
				
				$(this).wrap("<div class='bg-item'></div>");
				
				
				
			} else {
				$(this).wrap("<div class='bg-item' style='display:none;'></div>");
			}
			
			
		});
		
		slider.attr("last",$(this).find("img").size()-1);
		
	})
	$(window).bind("resize", resize);
	resize();
	showBackground($('div.menuContentTab').find('a:first').attr('href') + '_img');
	blocker=false;
	$("#skipVideo").click(function () {
		removeFlashVideo();
		return false;
	})
	
	

	
	
	
}

function homepageAutoRotate() {

	$(window).blur(function(){
	    clearTimeout(timer)   
	}).focus(function(){
	     timer = setTimeout("moveNext()", 6000);   
	});	

    timer = setTimeout("moveNext()", 6000);
}

function moveNext() {
	
	var links = $("#genreTab").find("a");
	
	var len = links.size();
	a++;
	if (a>=len) a=0;
	
	
	
	var newLink = links.get(a);
	
	$(newLink).parent().parent().find('li').removeClass('current');
	$(newLink).parent().addClass('current');
	$('div.tabContent').hide();
	$($(newLink).attr('href')).show();
	showBackground($(newLink).attr('href') + '_img');
	
	
	timer = setTimeout("moveNext()", 6000);
	
}

function resize() {
	var height = window.innerHeight ? window.innerHeight : $(window).height()
	var width = window.innerWidth ? window.innerWidth : $(window).width()
	if (mobile) {
		height = $(document).height();
	}
	resizeImg(width, height, $('#imgContainer'));
}

function resizeImg(sw, sh, targetContainer) {
	targetContainer.find("img").each(function () {
		var imgw = 1024;
		var imgh = 768;
		if ((sh / sw) > (imgh / imgw)) {
			img_prop = imgw / imgh;
			destHeight = sh;
			destWidth = sh * img_prop;
		} else {
			img_prop = imgh / imgw;
			destWidth = sw;
			destHeight = sw * img_prop;
		}
		$(this).attr({
			width: destWidth,
			height: destHeight
		});
		/*var xVal = sw * .5 - $(this).width() * .5;
		var yVal = sh * .5 - $(this).height() * .5;
		$(this).css({
			left: xVal,
			top: yVal
		});*/
	});
}

function showBackground(image) {
	blocker = true;
	var speed = 1500;
	if (initLoad) {
		initLoad = false;
		speed = 0;
	}
	var params = {
		fadeInSpeed: speed,
		center: true
	};
	//alert($(image).get(0));
	var width = window.innerWidth ? window.innerWidth : $(window).width()
	var slider = $(image).parent().parent();
	var current = slider.attr("index");
	var index = $(image).attr("index");
	var curItem = $("#"+slider.attr("current")).parent();
	var newItem = $(image).parent();

	if (("#"+slider.attr("current"))!==image) {
	  //alert(curItem!==newItem);
	  
	 
	  if ((index>current) || ((index==0) && (current==slider.attr("last")))) {
		
		   newItem.show().css("left",width+"px").animate({left: "0px"}, 1000, 'linear');
		   curItem.animate({left: "-"+width+"px"}, 1000, 'linear', function () {
			   curItem.hide();
			   blocker = false;
	       });
		
		
	  } else {
	   newItem.show().css("left","-"+width+"px").animate({left: "0px"}, 1000, 'linear');
	   curItem.animate({left: width+"px"}, 1000, 'linear', function () {
			curItem.hide();
			blocker = false;
	   });
	  }
	  slider.attr("index",""+index+"");
	  slider.attr("current",$(image).attr("id"));
	}
	
	/*$(image).parent().parent().animate({
		left: '-' + $(image).parent().css('left')
	}, 1000);*/
	//$('#imgContainer').npFullBgImgInline($(image).get(0), params);
}
