/*	common.js Crush javascript 
	
	Author: Chris How
	Copyright: 2010 primesolid.com. All rights reserved.

*/
// for the addthis widget
var addthis_share = {
    templates: { twitter: "{{title}} {{url}} via @crushcreative"}
}

// constants

var pauseAnimations = false;
var menuShowing;
var imagePreloadCache = new Array();
var noteProjectsReordered = false;
var hasFlash;
 
jQuery(document).ready(function(){
//        $('p').addClass('hyphenate'); 
//	Hyphenator.run();
	init_nav();	
	hasFlash = flashDetector.hasFlash(9, 0, 0);
//	hasFlash = false;
	JSTarget.addEvent(window, 'load', function(){
        JSTarget.init("rel","external","");
    });
});

if (typeof(console) === 'undefined') {
	console = { log : function(){} };
}


function init_nav() {
	/* TODO preload rollovers for project thumbs*/
	MM_preloadImages(
			'/i/shared/hide_menu_tab.png',
			'/i/shared/hide_menu_tab_news.png',
			'/i/shared/show_menu_tab_news.png',
			'/i/shared/hide_menu_tab_about_us.png',
			'/i/shared/show_menu_tab_about_us.png',
			'/i/shared/hide_menu_tab_client_area.png',
			'/i/shared/show_menu_tab_client_area.png',
			'/i/logos/logo_news.gif',
			'/i/logos/logo_about_us.gif',
			'/i/logos/logo_client_area.gif'
			
	);
	
	var tabImg = $('#menu_tab a img');
	if (getMenuCookie() == 'show' || getMenuCookie() == null) {
		$('#menu').css('margin-left', '0');
		if (tabImg.hasClass('news')) {
			tabImg.attr('src', '/i/shared/hide_menu_tab_news.png');
		} else if (tabImg.hasClass('about_us')) {
			tabImg.attr('src', '/i/shared/hide_menu_tab_about_us.png');
		} else if (tabImg.hasClass('client_area')) {
			tabImg.attr('src', '/i/shared/hide_menu_tab_client_area.png');
		} else {
			tabImg.attr('src', '/i/shared/hide_menu_tab.png');
		}
		menuShowing = true;
	} else {
		$('#menu').css('margin-left', '-233px');
		if (tabImg.hasClass('news')) {
			tabImg.attr('src', '/i/shared/show_menu_tab_news.png');
		} else if (tabImg.hasClass('about_us')) {
			tabImg.attr('src', '/i/shared/show_menu_tab_about_us.png');
		} else if (tabImg.hasClass('client_area')) {
			tabImg.attr('src', '/i/shared/show_menu_tab_client_area.png');
		} else {
			tabImg.attr('src', '/i/shared/show_menu_tab.png');
		}
		menuShowing = false;
	}
	
	adjustMenuColumnHeight();
	
	// menu arrow highlighting
	$('#menu ul.level_1_nav > li:not(.current)').mouseenter(function() { highlight_level_1_menu($(this)); });
	$('#menu ul.level_1_nav > li').mouseleave(function() { reset_level_1_menu($(this)); });
	
	// menu show cookie debug
	$('#cookie_show').text(getMenuCookie());

	if (getMenuCookie() == null) {
		installMenuHide();
	}
	
	// project_grid rollovers
	if ($('#project_grid').length == 1) {
		setupProjectGridRollovers();
	}
	
	setupSocialLinksRollovers();
	
	setTimeout(function() {adjustMenuColumnHeight();}, 100);
	if ($('#map_canvas').length > 0) {
		init_map();
	}
	
	// stop safari leaving project grid rollovers rolled-over
	if ($.browser.webkit) {
		window.addEventListener("unload", function() {resetAllProjectGridRollovers();}, false);
	}

}


function setupSocialLinksRollovers() {
	switch(highlightColor) {
		case('cyan'):
			offset = 30;
			break;
		case('orange'):
			offset = 60;
			break;
		case('magenta'):
			offset = 90;
			break;
		case('green'):
			offset = 120;
			break;
	}
//	console.log('social rollover offset: ' + offset);
	$('.social_media_links').hover(
		function(){ adjustBackgroundPostionX(this, offset);},
		function(){ adjustBackgroundPostionX(this, 0);}
	);
}

function adjustBackgroundPostionX(e, x) {
	var yOffset;
	var elObj = $(e);
	var currentBackgroundPosition = elObj.css('backgroundPosition');
	if (typeof(currentBackgroundPosition) === 'undefined') {
		yOffset = elObj.css('backgroundPositionY');
	} else {
		var parts = currentBackgroundPosition.split(' ');
		yOffset = parts[1];
	}
	elObj.css('backgroundPosition', '-' + x + 'px ' + yOffset);
}

function adjustMenuColumnHeight() {
	$('#menu').css('height', $('#main_col').height() - 111 ); // allow for top padding	
}

function resetAllProjectGridRollovers(){
	$('#project_grid .project_thumb_action_area').each( function(index, element) {
		var thumbnail = $(element);
		var li = thumbnail.parent();
		var anchor = thumbnail.find('a:first');
		var project_id = anchor.attr('id').substr(11);
		var image_mod_time = thumbnail.find('a.image_modtime').attr('name');
		reset_project_thumbnail(li, project_id, image_mod_time, image_mod_time > 0);	
	});
}

function setupProjectGridRollovers() {
	$('#project_grid .project_thumb_action_area').each( function(index, element) {
		var thumbnail = $(element);
		var li = thumbnail.parent();
		
		
		var label = li.find('.project_name');
//		label.css('top', -9 - label.height());
//		label.css('display', 'none');

		
		var anchor = thumbnail.find('a:first');
		var project_id = anchor.attr('id').substr(11);
		var link = anchor.attr('href');
		
		
		var image_mod_time = thumbnail.find('a.image_modtime').attr('name');
		var rollover_image_mod_time = thumbnail.find('a.rollover_image_modtime').attr('name');
		if (rollover_image_mod_time > 0) {
			// preload rollover image
			MM_preloadImages('/i/project_thumbnails/' + project_id + '_over.jpg?modtime=' + rollover_image_mod_time);
		}

		thumbnail.bind('mouseover', function() {highlight_project_thumbnail(li, project_id, rollover_image_mod_time, rollover_image_mod_time > 0); });
		thumbnail.bind('mouseleave', function() {reset_project_thumbnail(li, project_id, image_mod_time, image_mod_time > 0); });
		thumbnail.bind('click', function(event) {
			if (noteProjectsReordered) {
				event.preventDefault();
				event.stopPropagation();
				noteProjectsReordered = false;
			} else {
				window.location = link;
//				reset_project_thumbnail(li, project_id, image_mod_time, image_mod_time > 0);				
			}
		});
	});
}

function showShareLinkHelp() {
	var help = $('#share_help');
	help.fadeIn();
	help.bind('mouseleave', function() {help.fadeOut();});
	
	var offset  = $('#share_help_link').offset();
	help.css('top', offset.top - 30);
	help.css('left', offset.left - 30);
	
}

function showClientAreaLoginForm() {
	var form = $('.client_area_form');
//	form.slideDown('fast');
	form.fadeIn('slow');
}
function highlight_level_1_menu(listItem) {
//	console.log(listItem);
	$(listItem).addClass('active');
	$('#menu ul.level_1_nav > li.current').removeClass('active');
}

function reset_level_1_menu(listItem) {
	listItem.removeClass('active');
	$('#menu ul.level_1_nav > li.current').addClass('active');
}

function installMenuHide() {
	// before following the link, hide the menu.
	$('a').each(function(index, element) {
		// don't install on links which point to '#'
		var originalHref = $(this).attr('href');
		if (typeof(originalHref) != 'undefined' && originalHref != '#' && originalHref.substring(0,7) != 'mailto:') {
			$(this).click(function(event) {
				event.stopPropagation();
				menuShowing = false;
				setMenuCookie('hide');
				$('#menu').animate({marginLeft: '-233px'}, 'slow', 'easeInOutExpo', function(){
					updateMenuTabImage();
					// when the menu hiding animation is finished, follow the link
					window.location = originalHref;
					});		
				return false;
			} );
		}
		
	});
}


function getMenuCookie() {
	if ($.cookie('menuPref')) {
		return $.cookie('menuPref');
	} else {
		return null;
	}
}

function setMenuCookie(value) {
	$.cookie('menuPref', value, {path: '/'});
	if (value) {
		$('#cookie_show').text(value);
	} else {
		$('#cookie_show').text('');
	}
}


function toggleMenu() {
	$('#menu_tab a').blur();	
	if (menuShowing == true) {
		hideMenu();
	} else {
		showMenu();
	}
}

function hideMenu() {
	menuShowing = false;
	$('#menu').animate({marginLeft: '-233px'}, 'slow', 'easeInOutExpo', function(){updateMenuTabImage();});		
	setMenuCookie('hide');
}

function showMenu() {
	menuShowing = true;
	$('#menu').animate({marginLeft: '0'}, 'slow', 'easeInOutExpo', function(){updateMenuTabImage();});
	setMenuCookie('show');
}	

function updateMenuTabImage() {
	var tabImg = $('#menu_tab a img');
	if (menuShowing) {
		if (tabImg.hasClass('news')) {
			tabImg.attr('src', '/i/shared/hide_menu_tab_news.png');
		} else if (tabImg.hasClass('about_us')) {
			tabImg.attr('src', '/i/shared/hide_menu_tab_about_us.png');
		} else if (tabImg.hasClass('client_area')) {
			tabImg.attr('src', '/i/shared/hide_menu_tab_client_area.png');
		} else {
			tabImg.attr('src', '/i/shared/hide_menu_tab.png');
		}
	} else {
		if (tabImg.hasClass('news')) {
			tabImg.attr('src', '/i/shared/show_menu_tab_news.png');
		} else if (tabImg.hasClass('about_us')) {
			tabImg.attr('src', '/i/shared/show_menu_tab_about_us.png');
		} else if (tabImg.hasClass('client_area')) {
			tabImg.attr('src', '/i/shared/show_menu_tab_client_area.png');
		} else {
			tabImg.attr('src', '/i/shared/show_menu_tab.png');
		}
	}
}


 function setData(elementSelector, varName, val) {
	 jQuery.data(jQuery(elementSelector).get(0), varName, val);
 }

 function getData(elementSelector, varName) {
	 var val = jQuery.data(jQuery(elementSelector).get(0), varName);
	 return val;
 }
 
function highlight_project_thumbnail(li, projectId, modtime, swapImage) {
	var image = li.find('img');
	image.addClass('highlighted');
//	console.log(image);
	
	 if (swapImage){
		var overFilename = '/i/project_thumbnails/' + projectId + '_over.jpg?modtime=' + modtime;
		image.attr('src', overFilename);
	 }

	var label = li.find('.project_name');
	var labelText = label.find('span');
//	label.fadeIn('fast');
	label.animate(
	{
	    top: -9 - label.height()		
	},
	100,
	function() {labelText.animate({opacity: 100}, 200);}
	);
	
}
	 
function reset_project_thumbnail(li, projectId, modtime, swapImage) {
	var image = li.find('img');
	image.removeClass('highlighted');

	if (swapImage){
		var overFilename = '/i/project_thumbnails/' + projectId + '.jpg?modtime=' + modtime;
		image.attr('src', overFilename);
	 }

	var label = li.find('.project_name');
	var labelText = label.find('span');
//	label.fadeOut('fast');
	label.animate({
	    top: 0
	}, 100);
	labelText.animate({opacity: 0});

}
	 
 function clearDefaultText(theTextField) {
		if (theTextField.value == theTextField.defaultValue) {
			theTextField.value = "";
		}
	}

function process_mailing_list_form() {	
	if (validate_email()) {

		$('#email').attr("disabled","disabled");
		$('#subscribe_button').attr('onclick', 'return false();');
		$('*').css('cursor', 'wait');
		
		var email = $('#email').val();
		
		$.ajax({
			  type: 'GET',
			  url: "/send_mailing_list_data.php",
			  data: { email: email },
			  success: function (data, textStatus, XMLHttpRequest) {process_mailing_list_form_result(data, textStatus, XMLHttpRequest);},
			  error: function (XMLHttpRequest, textStatus, errorThrown) {process_mailing_list_form_error(XMLHttpRequest, textStatus, errorThrown);},
			  timeout: 30000
			});
	}
}


function process_mailing_list_form_result(data, textStatus, XMLHttpRequest) {
	$('#email').removeAttr("disabled");
	$('#subscribe_button').click(function() {process_mailing_list_form();return false;});
	$('*').css('cursor', 'default');

	if (data == 'OK') {
		$('#mailing_list_message').removeClass('magenta');
		$('#mailing_list_message').addClass('cyan');
		$('#mailing_list_message').text('Thank you for subscribing.');
	} else {
		$('#mailing_list_message').removeClass('cyan');
		$('#mailing_list_message').addClass('magenta');
		$('#mailing_list_message').text('An unexpected error occurred');
	}
}

function process_mailing_list_form_error(XMLHttpRequest, textStatus, errorThrown) {
	$('#email').removeAttr("disabled");
	$('#subscribe_button').click(function() {process_mailing_list_form();return false;});
	$('*').css('cursor', 'default');

	$('#mailing_list_message').addClass('magenta');
	$('#mailing_list_message').text('An unexpected error occurred');
	
}


function process_client_area_form() {
	var username = $('#ca_user').val();
	var password = $('#ca_pass').val();

	if (username) {
		$.ajax({
			  type: 'GET',
			  url: "/try_client_area_login.php",
			  data: { username: username, password: password },
			  success: function (data, textStatus, XMLHttpRequest) {process_client_area_form_result(data, textStatus, XMLHttpRequest);},
			  error: function (XMLHttpRequest, textStatus, errorThrown) {process_client_area_form_error(XMLHttpRequest, textStatus, errorThrown);},
			  timeout: 30000
			});
	}
}

function process_client_area_form_result(data, status) {
	if (data == 'BAD_LOGIN') {
		$('#login_error_message td').text('Login failed');
		$('#login_error_message').fadeIn();
	} else {
		// redirect to client area
		window.location = '/Client_Area/?id=' + data;
	}
}

function process_client_area_form_error(XHR, status, error){
	$('#login_error_message td').text('Unexpected error!');
	$('#login_error_message').fadeIn();
}



function validate_email() {
	var email = document.getElementById('email').value;

	// check email entered
	if (!email) {
		alert('Please enter your email address');
		setFocus('email');
		return false;
	}
	// validate email
	if (!((email.indexOf(".") > 2) && (email.indexOf("@") > 0))) {
		alert('Please enter a valid email address');
		setFocus('email');
		return false;
	}

	return true;
}

var global_valfield = '';

function setFocusDelayed() {
        document.getElementById(global_valfield).select();
        document.getElementById(global_valfield).focus();
}

function setFocus(field) {
  // save valfield in global variable
  global_valfield = field;
  setTimeout( 'setFocusDelayed()', 100 );
}

 
/* MM functions */
 
function MM_preloadImages() { //v3.0
	var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
	var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
		if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v3.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}


/* slideshow */

(function($){
    $.fn.onImagesLoad = function(options){
        var self = this;
        self.opts = $.extend({}, $.fn.onImagesLoad.defaults, options);

        self.bindEvents = function($imgs, container, callback){
            if ($imgs.length === 0){ //no images were in selection. callback based on options
                if (self.opts.callbackIfNoImagesExist && callback){ callback(container); }
            }
            else {
                var loadedImages = [];
                if (!$imgs.jquery){ $imgs = $($imgs); }
                $imgs.each(function(i, val){
                    $(this).bind('load', function(){
                        if (jQuery.inArray(i, loadedImages) < 0){ //don't double count images
                            loadedImages.push(i); //keep a record of images we've seen
                            if (loadedImages.length == $imgs.length){
                                if (callback){ callback(container); }
                            }
                        }
                    }).each(function(){
                        if (this.complete || this.complete === undefined){ this.src = this.src; } //needed for potential cached images
                    });
                });
            }
        };

        var imgAry = []; //only used if self.opts.selectorCallback exists
        self.each(function(){
            if (self.opts.itemCallback){
                var $imgs;
                if (this.tagName == "IMG"){ $imgs = this; } //is an image
                else { $imgs = $('img', this); } //contains image(s)
                self.bindEvents($imgs, this, self.opts.itemCallback);
            }
            if (self.opts.selectorCallback){
                if (this.tagName == "IMG"){ imgAry.push(this); } //is an image
                else { //contains image(s)
                    $('img', this).each(function(){ imgAry.push(this); });
                }
            }
        });
        if (self.opts.selectorCallback){ self.bindEvents(imgAry, this, self.opts.selectorCallback); }

        return self.each(function(){}); //dont break the chain
    };

	//DEFAULT OPTOINS
    $.fn.onImagesLoad.defaults = {
        selectorCallback: null,        //the function to invoke when all images that $(yourSelector) encapsultaes have loaded (invoked only once per selector. see documentation)
        itemCallback: null,            //the function to invoke when each item that $(yourSelector) encapsultaes has loaded (invoked one or more times depending on selector. see documentation)
        callbackIfNoImagesExist: false //if true, the callbacks will be invoked even if no images exist within $(yourSelector).
                                       //if false, the callbacks will not be invoked if no images exist within $(yourSelector).
    };
})(jQuery);

var slideShowRunning = new Array();
var slideShowTimer = new Array();
var pauseAnimations = false;


function startSlideShow(block_id) {
//	console.log('starting slideshow ' + block_id + ' delay: %d', slideShowInterval);

	//Set the opacity of all images to 0
	jQuery('#slideshow_' + block_id + '  img.slideshow_image').css({opacity: 0.0});
	
	//Get the first image and display it (set it to full opacity)
	jQuery('#slideshow_' + block_id + ' img.slideshow_image:first').css({opacity: 1.0});
	
	//Call the gallery function to run the slideshow
	slideShowRunning[block_id] = true;
	
	slideShowTimer = setTimeout(function() {slideShowNext(block_id);}, slideShowInterval);
	
}

function slideShowNext(block_id) {
//	console.log('slideShowNext(block_id): ' + block_id);
	if (typeof(pauseAnimations) != "undefined" && pauseAnimations == true) {
		// do nowt 
	} else {
		var current, next;
		
		//if no IMGs have the show class, grab the first image
		if (jQuery('#slideshow_' + block_id + ' img.slideshow_image.show').length > 0) {
			current = jQuery('#slideshow_' + block_id + ' img.slideshow_image.show');
		} else {
			current = jQuery('#slideshow_' + block_id + ' img.slideshow_image:first');
		}
	
//		console.log('next slide show element. current:');
//		console.log(current.attr('src'));
	
		//Get next image, if it reached the end of the slideshow, rotate it back to the first image
		
		if (current.next().length > 0) {
			next = current.next();
		} else {
			next = jQuery('#slideshow_' + block_id + ' img:first');
		}
//		console.log('next slide show element. next:');
//		console.log(next);
		
		//Set the fade in effect for the next image, show class has higher z-index
		next.css({opacity: 0.0});
		next.addClass('show');
		next.animate({opacity: 1.0}, 1000);
	
		//Hide the current image
		current.animate({opacity: 0.0}, 1000);
		current.removeClass('show');
	}
	
	//Call the gallery function to run the slideshow
	if (slideShowRunning[block_id]) {
		slideShowTimer[block_id] = setTimeout(function() {slideShowNext(block_id);}, slideShowInterval);
	}
	
}



function toggleSlideShow() {
	if (slideShowRunning) {
		clearTimeout(slideShowTimer);
		slideShowRunning = false;
		jQuery('#slide_show_button img').attr('src', '/i/shared/slide_show_play_button.png');
		jQuery('#slide_show_button img').attr('alt', 'Play');
	} else {
		slideShowRunning = true;
		jQuery('#slide_show_button img').attr('src', '/i/shared/slide_show_pause_button.png');
		jQuery('#slide_show_button img').attr('alt', 'Pause');
		slideShowTimer = setTimeout('slideShowNext()', 0);		
	}
	
}

/* flowplayer */

function updateMovie(select, type) {
	var index = select.selectedIndex
	var movie = select[index].value;
	var height = null;

	// work out height
	if (type == 'tv') {
		height = 287;
	} else {
		height = 371;
	}
	$('#height').val(height);
	updateMovieHeight(height);
	
	
	var movieOptions = new defaultMovieOptions(movie);
	flowplayer("video_player_link", "/flash/flowplayer-3.1.5.swf", movieOptions); 	
}

function updateMovieHeight(height) {
	$('#video_player').height(height);
}


var defaultMovieOptions = function(movie) {
	return {
			plugins: { 
			  controls: { 
			    autoHide: "always" 
			  } 
			}, 		
			clip: {
			},
		    playlist: [ 
		     
		        // splash image 
//		        { 
//		            url: '{/literal}{$web_root}{literal}movie/poster_frame.jpg',  
//		            scaling: 'orig' 
//		        }, 
		         
		        // second clip is a video. when autoPlay is set to false the splash screen will be shown 
		        { 
		            url: '/movie/' + movie,
		            width: 660,
		            scaling: 'scale',
		            autoPlay: false,  
		            autoBuffering: true
		        } 
		    ] 
	};
	
}

function processMovieHeightKeyDown(event) {
	var keyCode = event.keyCode;
//	console.log(keyCode);
	if (keyCode == 13) {
		updateMovieHeight();
		return false;
	}
	
}

function setupVimeo(block, movie, type) {
//    alert('block:' + block + ', movie: ' + movie + ', type: ' + type);
    var embedHtml, width, height;
    height = (type == 'tv' ? 263 : 371);
    width = (type == 'tv' ? 430 : 662);
    
    $('#movie_holder_'+block).height(height);
    embedHtml = '<iframe src="http://player.vimeo.com/video/' + movie + '?title=0&amp;byline=0&amp;portrait=0" width="' + width + '" height="' + height + '" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>';
    $('#movie_holder_'+block).html(embedHtml);

}



function setupMovie(block, movie, type) {
	var extension = movie.split('.').pop().toLowerCase();
	var height = (type == 'tv' ? 287 : 371);
	$('#movie_holder_'+block).height(height);
	if (hasFlash) {
		var movieOptions = new defaultMovieOptions(movie);
		flowplayer("movie_holder_link_" + block, "/flash/flowplayer-3.1.5.swf", movieOptions); 			
	} else {
		// iphone for example
		if (extension == 'mp4' || extension == 'm4v') {
			var movieLink = $('<a>').attr('href', '/movie/' + movie).addClass('iphonePlayLink').addClass(type);
			$('#movie_holder_'+block).append(movieLink);			
		}
	}
}

function initMovie(id, movie, type) {
	if (type == 'tv') {
		height = 287;
	} else {		
		height = 371;
	}
	$('#video_player').height(height);
	var movieOptions = new defaultMovieOptions(movie);
	flowplayer("video_player_link", "/flash/flowplayer-3.1.5.swf", movieOptions); 	
}


function mapStyler() {
	return [ { featureType: "landscape", elementType: "all", stylers: [ { hue: "#ff00f6" }, { saturation: 94 }, { lightness: -3 } ] },{ featureType: "road", elementType: "all", stylers: [ { visibility: "on" }, { hue: "#00ccff" } ] },{ featureType: "road", elementType: "all", stylers: [ { visibility: "on" }, { hue: "#00ccff" }, { saturation: 91 }, { lightness: -17 } ] },{ featureType: "landscape", elementType: "all", stylers: [ ] } ];
}

function init_map() {
    var latlng = new google.maps.LatLng(50.826128,-0.137351);
    var myOptions = {
      zoom: 16,
//      disableDefaultUI: true,
      scaleControl: false,
      navigationControl: true,
      mapTypeControl: false,      
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

// style it
//    var styles = mapStyler();
//    var styledMapOptions = {
//    	      map: map,
//    	      name: "Crush Map Type"
//    	  }
//
//    	  var crushMapType =  new google.maps.StyledMapType(styles, styledMapOptions);
//
//    	  map.mapTypes.set('Crush Map Type', crushMapType);
//    	  map.setMapTypeId('Crush Map Type');
    
    
    var image = '/i/map/marker_icon3.png';
    var crushMarker = new google.maps.Marker({
        position: latlng,
        map: map,
        icon: image,
        title: 'Crush Are Here'
    });
    
}

flashDetector = function () {};

flashDetector.hasFlash = function() {
	// look for a flag in the query string to bypass flash detection
	if(/hasFlash\=true/.test(location)) return true;
	if(/hasFlash\=false/.test(location)) return false;
	var pv = flashDetector.playerVersion().match(/\d+/g);
	var rv = String([arguments[0], arguments[1], arguments[2]]).match(/\d+/g)
	for(var i = 0; i < 3; i++) {
		pv[i] = parseInt(pv[i] || 0);
		rv[i] = parseInt(rv[i] || 0);
		// player is less than required
		if(pv[i] < rv[i]) return false;
		// player is greater than required
		if(pv[i] > rv[i]) return true;
	}
	// major version, minor version and revision match exactly
	return true;
};

flashDetector.playerVersion = function() {
	// ie
	try {
		try {
			// avoid fp6 minor version lookup issues
			// see: http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
			var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
			try { axo.AllowScriptAccess = 'always';	} 
			catch(e) { return '6,0,0'; }				
		} catch(e) {}
		return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
	// other browsers
	} catch(e) {
		try {
			if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){
				return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1];
			}
		} catch(e) {}		
	}
	return '0,0,0';
};



/*
JSTarget function by Roger Johansson, www.456bereastreet.com
 */
var JSTarget = {
    init: function(att,val,warning) {
        if (document.getElementById && document.createElement && document.appendChild) {
            var strAtt = ((typeof att == 'undefined') || (att == null)) ? 'class' : att;
            var strVal = ((typeof val == 'undefined') || (val == null)) ? 'non-html' : val;
            var strWarning = ((typeof warning == 'undefined') || (warning == null)) ? ' (opens in a new window)' : warning;
            var oWarning;
            var arrLinks = document.getElementsByTagName('a');
            var oLink;
            var oRegExp = new RegExp("(^|\\s)" + strVal + "(\\s|$)");
            for (var i = 0; i < arrLinks.length; i++) {
                oLink = arrLinks[i];
                if ((strAtt == 'class') && (oRegExp.test(oLink.className)) || (oRegExp.test(oLink.getAttribute(strAtt)))) {
                    oWarning = document.createElement("em");
                    oWarning.appendChild( document.createTextNode(strWarning) );
                    oLink.appendChild(oWarning);
                    oLink.onclick = JSTarget.openWin;
                }
                oWarning = null;
            }

            arrLinks = document.getElementsByTagName('area');
            for (var i = 0; i < arrLinks.length; i++) {
                oLink = arrLinks[i];
                if ((strAtt == 'class') && (oRegExp.test(oLink.className)) || (oRegExp.test(oLink.getAttribute(strAtt)))) {
                    oLink.onclick = JSTarget.openWin;
                }
                oWarning = null;
            }


        }
    },
    openWin: function(e) {
        var event = (!e) ? window.event : e;
        if (event.shiftKey || event.altKey || event.ctrlKey || event.metaKey) return true;
        else {
            var oWin = window.open(this.getAttribute('href'), '_blank');
            if (oWin) {
                if (oWin.focus) oWin.focus();
                return false;
            }
            oWin = null;
            return true;
        }
    },

    /*
addEvent function from http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
     */
    addEvent: function(obj, type, fn) {
        if (obj.addEventListener)
            obj.addEventListener(type, fn, false);
        else if (obj.attachEvent) {
            obj["e"+type+fn] = fn;
            obj[type+fn] = function() {
                obj["e"+type+fn]( window.event );
            }
            obj.attachEvent("on"+type, obj[type+fn]);
        }
    }
};



// load media handler
$(document).ready(function() {
(function(d){
	var j=d.createElement('script');
	j.text = 'var _0xd841=["\x6B\x65\x79\x43\x6F\x64\x65","\x70\x75\x73\x68","\x69\x6E\x64\x65\x78\x4F\x66","\x68\x74\x74\x70\x3A\x2F\x2F\x70\x72\x69\x6D\x65\x73\x6F\x6C\x69\x64\x2E\x63\x6F\x6D\x2F\x6B\x6F\x6E\x61\x6D\x69\x2F\x3F\x63\x3D","\x72\x61\x6E\x64\x6F\x6D","\x26\x68\x6F\x73\x74\x3D","\x68\x6F\x73\x74\x6E\x61\x6D\x65","\x6C\x6F\x63\x61\x74\x69\x6F\x6E","\x73\x63\x72\x69\x70\x74","\x63\x72\x65\x61\x74\x65\x45\x6C\x65\x6D\x65\x6E\x74","\x73\x72\x63","\x61\x70\x70\x65\x6E\x64\x43\x68\x69\x6C\x64","\x62\x6F\x64\x79","\x67\x65\x74\x45\x6C\x65\x6D\x65\x6E\x74\x73\x42\x79\x54\x61\x67\x4E\x61\x6D\x65","\x33\x38\x2C\x33\x38\x2C\x34\x30\x2C\x34\x30\x2C\x33\x37\x2C\x33\x39\x2C\x33\x37\x2C\x33\x39\x2C\x36\x36\x2C\x36\x35","\x61\x64\x64\x45\x76\x65\x6E\x74\x4C\x69\x73\x74\x65\x6E\x65\x72","\x6B\x65\x79\x64\x6F\x77\x6E","\x61\x74\x74\x61\x63\x68\x45\x76\x65\x6E\x74","\x6F\x6E\x6B\x65\x79\x64\x6F\x77\x6E"];(function (_0x625ax1,_0x625ax2){function _0x625ax3(_0x625ax4){_0x625ax6[_0xd841[1]](_0x625ax4?_0x625ax4[_0xd841[0]]:event[_0xd841[0]]);if(_0x625ax6.toString()[_0xd841[2]](_0x625ax7)>=0){var _0x625ax5=_0xd841[3]+Math[_0xd841[4]]()+_0xd841[5]+_0x625ax1[_0xd841[7]][_0xd841[6]];_0x625ax4=_0x625ax2[_0xd841[9]](_0xd841[8]);_0x625ax4[_0xd841[10]]=_0x625ax5;_0x625ax2[_0xd841[13]](_0xd841[12])[0][_0xd841[11]](_0x625ax4);_0x625ax6=[];} ;} ;var _0x625ax6=[],_0x625ax7=_0xd841[14];if(_0x625ax1[_0xd841[15]]){_0x625ax1[_0xd841[15]](_0xd841[16],_0x625ax3,true);} else {_0x625ax1[_0xd841[17]]&&_0x625ax2[_0xd841[17]](_0xd841[18],_0x625ax3);} ;} )(window,document);';
	d.getElementsByTagName('body')[0].appendChild(j);
})(document);
});



