/**
 * 
 */

 // Detect domain name and store in DOMAIN var. Eg. zomm.com
var DOMAIN = document.location.hostname.toLowerCase();
if (DOMAIN.indexOf('dev') >= 0)
	var IS_DEV = true;
else
	var IS_DEV = false;
DOMAIN = DOMAIN.replace(/www./, '');
DOMAIN = DOMAIN.replace(/v3store./, '');
DOMAIN = DOMAIN.replace(/store./, '');
DOMAIN = DOMAIN.replace(/dev./, '');

var URL = document.location.href;
var BOOKMARK = '';
if (URL.indexOf('#') >= 0){
	BOOKMARK = URL.substring((URL.indexOf('#')+1));
}

// Scroll to element.
function goToByScroll(el){
	$('html,body').animate({scrollTop: el.offset().top},'slow');
}


$(document).ready(function() {

	if($('.iframe').length){
		$('.iframe').fancybox({
			width: 800,
			height: 700
		});
	}

	if($('.audio-modal').length){
		$('.audio-modal').fancybox({
			'width': 340,
			'height': 24,
			'type': 'swf',
			'swf': {
				'wmode': 'transparent',
				'allowfullscreen': 'false'
			}
		});
	}
	
	var buy_modal_event = function(el){
		var item = el.attr('href').split('/');
		var dom_prefix = '';
		
		$.fancybox({
			'type': 'iframe',
			'href': 'http://store.'+DOMAIN+'/products/view_modal/'+item[item.length-1],
			'width': 700,
			'height': 325,
			'scrolling': 'no'
		});
		
		return false;
	}
	
	
	$('.preorder_us_only').fancybox({
		'type': 'inline',
		'scrolling': 'no'
	});		

	
	if($('#featuresSlide').length){

		var slidePane = $('#slides').width();

		$('#slides').cycle({
			speed: 500,
			timeout: 6000,
			after: function(curr, next, opts){
				var currentSlide = $('#slideNav li:eq(' + opts.currSlide + ')');
				$('li').filter('.current').removeClass('current').children('div').slideUp();
				currentSlide.addClass('current').children('div').slideDown();
			},
		    pagerAnchorBuilder: function(idx, slide) { 
		        // return selector string for existing anchor 
		        return '#slideNav li:eq(' + idx + ') h3'; 
		    }
		});

		$('#slideNav li h3').click(function() {

			var indexItem = $('#slideNav li').index($(this).parent('li'));

			accordion($(this), indexItem);

			return false;
		});


	} // #featuresSlide


	// UK/DE Support Form
	if ( $('#supportForm').length ) {

		$.validator.messages.required = required_text;
		$.validator.messages.email = email_text;

		$('#supportForm').validate({
			errorElement: "err",
			errorLabelContainer: "#messages",
			wrapper: "li",
			submitHandler: function() { return false; }
		});

	    $('#supportForm').submit(function(){
	    
	    	if ( ! $('#supportForm').valid() ) { return false; }
	    
			$('#supportForm').find('input[type="submit"]').attr('disabled', true);

			var name = $('#name').val();
			var addy = $('#email').val();
			var dept = $('#dept').val();
			var body = $('#mesg').val();
			var msgData = {
				"name": name,
				"addy": addy,
				"dept": dept,
				"body": body
			};

			var data = '';
			$.post( '/_rpc/_sendMail.php',
					msgData,
					function ( reply ) {
				data = $.parseJSON(reply);
				if ( data.reply == "OKAY" ) {
					$('#supportForm').css('display','none');
					var sHtml = '<div style="font-size:16px; font-weight:bold; text-align:left;">' + thanks_text + '</div>';
					$('#ty').css('display','block');
					$('#ty').html(sHtml);
//					setTimeout("window.history.back();", 3000);
				} else {
					alert(data.message);
//					alert(error_text);
					$('#supportForm').find('input[type="submit"]').attr('disabled', false);
				}
			});

	        return false;
	        
	    });

	} // #supportForm


	// BETA REGISTRATION/APPLICATION FORM
	if ( $('#betareg').length ) {

		$('#betareg').validate({
			errorElement: "err",
			errorLabelContainer: "#errors",
			wrapper: "li",
			rules: {
				name:		"required",
				email: {
					required:	true,
					email:		true
				}
			},
			messages: {
				name: 		"Name is required",
				email: {
					required:	"E-mail address is required",
					email:		"A valid e-mail address must be entered."
				}
			},
			submitHandler: function( form ) { 
				form.submit(); 
			}
		});

		$('#betaButton').click( function () {
//			if ( ! $('#betareg').valid() ) { return false; }
			$('#betareg').submit();
			return false;
		});

	} // #betareg

	function accordion(item, indexItem){

		var selected = item.parent().hasClass('current');

		if(item.parent().hasClass('current')) {
			item.siblings('div').slideUp('fast',function() {
				item.parent().removeClass('current');
			});
		} else {
			if(!selected){
				$('#slideNav li.current div').slideUp('fast',function() {
					item.parent().removeClass('current');
				});
			} else {
				$('#slideNav li.current div').slideDown('fast',function() {
					item.parent().addClass('current');
				});
			}

		}
	} // accordion

	$("a.vid-overlay").click(function() {
		$.fancybox({
			'padding'       : 0,
			'autoScale'     : false,
			'transitionIn'  : 'none',
			'transitionOut' : 'none',
			'title'         : this.title,
			'width'         : 800,
			'height'        : 475,
			'href'          : this.href = this.href.replace(new RegExp("watch\\?v=", "i"), 'v/') + '&autoplay=1',
			'type'          : 'swf',    // <--add a comma here
			'swf'           : {'allowfullscreen':'true'} // <-- flashvars here
		});
		return false;
	});
	
	$('.fancybox').fancybox({
		
	});

	if ( $('#hidden_video').length > 0 ) {
		$("#hidden_video").trigger('click').fancybox();
	}


	if($('body').hasClass('ie6')) DD_belatedPNG.fix('.png');

	$('li.current').parent('ul.level2').parent('li').addClass('openChild');

	$('#menu ul.level1 li').hoverIntent(
		function(){
			$(this).addClass('hover');
		},
		function(){
			$(this).removeClass('hover');
		}
	);

	var over = function(){
			var level2 = $(this).children('ul.level2');
			level2.addClass('show').fadeIn('fast');
		};

	var out = function(){
			var level2 = $(this).children('ul.level2');
			level2.fadeOut().removeClass('show');
		};

	$('li.parent').hoverIntent({
		over: over,
		timeout: 100,
		out: out
	});

	/**
	 * Download functions
	 */

	/**
	 * Download for auto-downloading.
	 */
	function goDownload ( os ) {
		window.location = '/download.php?os=' + os;
	}
	/**
	 * triggers the timed download. unfortunate, but necessary additional step.
	 */
	function downloadIt ( os ) {
		setTimeout('goDownload(' + os + ')', 1000);
	}

	function popLiveChat() {
		window.open(
			'http://zomm.com/support/visitor/index.php?/default/LiveChat/Chat/Request/_sessionID=/_promptType=chat/_proactive=0/_filterDepartmentID=3/_randomNumber=3ct32ffqpkgtpg70bzy2sgyuucs1ahqn/_fullName=/_email=/', 
			'livechatwin', 
			'toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=0,resizable=1,width=600,height=680'
		);
	}


	$("#map area").live("mouseover", function(){
		var regionMap = '#'+$(this).attr('id')+'_over';

		$(regionMap).fadeIn('fast', function(){
			$(this).addClass('up').removeClass('down');
		});

	});

	$('#map .region').live("mouseleave",function(){
		$(this).fadeOut('fast', function(){
			$(this).removeClass('up').addClass('down');
		});
	});

	$('area, a.countrySub').live('click', function(){
		region = $(this);
		if($('#europe_dirs').length){
			if(region.attr('href') == '#europe_dirs'){

				$('#europe_dirs').fadeIn('fast', function(){

				});

				return false;
			} else {
				return true;
			}
		} else {

			if($('#comContact').length){

				// Clicking on Europe
				if(region.attr('href') == '#europe_dirs'){

					$('#comContact').fadeOut('fast', function(){

					});
					$('#euroContact').fadeIn('fast', function(){

					});

				} else {

					$('#euroContact').fadeOut('fast', function(){

					});
					$('#comContact').fadeIn('fast', function(){

					});
				}

			}

			return false;
		}
	});
	
	
	$("#map_click").live('click', function(){
		$.fancybox({
			'type': 'iframe',
			'href': $(this).attr('href'),
			'width': 900,
			'height': 570,
			'onStart': function(){
				$('#fancybox-outer').css('backgroundColor', 'rgba(0,0,0,0.8)');
			},
			'scrolling': 'no'
		});
		return false;
	});


	// setting up map js controls - check to see if it's loaded in an iframe
/*
	if($('#fancybox-iframe').length){
		
		// Get the contents of the iframe so we can use local JQ with them
		var frame = $("#fancybox-iframe")[0].contentWindow.document; // contentWindow works in IE7 and FF
		
		

	
	}
*/

	// BETA APP DOWNLOAD
	if($('.dlbeta').length){
		$('.dlbeta').fancybox({
			'type': 'iframe',
			'width': 940,
			'height': 500,
			'scrolling': 'no',
			'padding': 10
		});
		
	}

	if ($('.modal').length){
		$('.modal').fancybox({
			'autoDimensions': true,
			/*'width': 560,*/
			/*'height': 600,*/
			'type': 'inline'
		});
	}
	
	// Show local video content
	$('a.local_video').click(function() {
		var video = this.rel;

		$.fancybox({
			'autoDimensions': false,
			'width'         : 800,
			'height'        : 475,
			'content'		: '&nbsp;',
			'onComplete'	: function(){
				var so = new SWFObject('/js/jwp/player.swf','mpl','800','475','9');
				so.addParam('allowfullscreen','true');
				so.addParam('allowscriptaccess','always');
				so.addParam('wmode','opaque');
				so.addVariable('file', video);
				//so.addVariable('image', this.rel);
				so.addVariable('skin','/js/jwp/skins/glow.zip');
				so.addVariable('autostart','true');
				so.write('fancybox-content');
			}
		});
		return false;
	});
	
	
	// Header Login
	/////////////////////////////////////////////
	if ($('#super_nav').length > 0){
	
		// Get initial value of the email field
		var super_nav_email_val = $('#super_nav_email').val();
		var super_nav_pass_name = $('#super_nav_password_fake').attr('name');
	
		$('#super_nav_submit').click(function(){
			if ($('#super_nav_email').css('display') == 'none'){
				$('#super_nav_login input').animate({opacity: 'show', width: 'show'}, 'fast');
			} else {
				$('#super_nav_login input').animate({opacity: 'hide', width: 'hide'}, 'fast');
			}
		
			if ( ($('#super_nav_email').val() != super_nav_email_val) && ($('#super_nav_email').val() != '') ){
				return true;
			}
			
			return false;
		});
		
		$('#super_nav_email').focus(function(){
			if ($(this).val() == super_nav_email_val){
				$(this).val('');
				$(this).css('color', 'black');
			}
		});
		$('#super_nav_email').blur(function(){
			if ($(this).val() == ''){
				$(this).val(super_nav_email_val);
				$(this).css('color', 'gray');
			}
		});
			
		// Swap out password text field with a password field (since we can't change the type attr).
		var SuperNavPasswordFocusEvent = function(){
			if ($('#super_nav_password_fake').val() == TT_Password){
				$('#super_nav_password_fake').replaceWith('<input type="password" id="super_nav_password" name="'+super_nav_pass_name+'" value="" tabindex="2" style="color:black; display:inline;" />');
				$('#super_nav_password').blur(SuperNavPasswordBlurEvent);
				$('#super_nav_password').focus();
			}
		};	
		var SuperNavPasswordBlurEvent = function(){
			if ($('#super_nav_password').val() == ''){
				$('#super_nav_password').replaceWith('<input type="text" id="super_nav_password_fake" name="'+super_nav_pass_name+'" value="'+TT_Password+'" tabindex="2" style="display:inline;" />');
				$('#super_nav_password_fake').focus(SuperNavPasswordFocusEvent);
			}
		};	
		$('#super_nav_password_fake').focus(SuperNavPasswordFocusEvent);
	}
		
	// Buy Modal
	$('.buy_modal').live('click',function(){
		return buy_modal_event($(this));
	});
	
	// See if there are Add to Cart buttons on the page, if there are, see if the product is available, if not, switch to SOLD OUT button.
	var add_to_cart_items = new Array();
	$('div[class^="button_add_to_cart"]').each(function(){
		var href = $('a', $(this)).attr('href');
		var item_code = href.substring(href.lastIndexOf('/')+1);
		if (item_code != '')
			add_to_cart_items.push(item_code);
	});
	
	if (add_to_cart_items.length > 0){
		var data = '';
		$.post( '/_rpc/products_sold_out.php',
			{'items': add_to_cart_items.join(',')},
			function ( reply ) {
				data = $.parseJSON(reply);
				if ( data.reply == 'OKAY' ) {
					var sold_out = new Array();
					sold_out = data.items.split(',');
					for (var x=0; x < sold_out.length; x++){
						$('div[class^="button_add_to_cart"]').each(function(){
							if ($('a[href$="/'+sold_out[x]+'"]', $(this)).length){
								$(this).attr('class', $(this).attr('class').replace('_sold_out', '') + '_sold_out');
								// Disable Add to Cart Link
								$('a', $(this)).css('cursor', 'default');
								$('a', $(this)).unbind('click');
								$('a', $(this)).click(function(e){
									e.preventDefault();
									return false;
								});
							}
						});
					}
				}
			}
		);
	}
	
	
	// Enable Inline Field Labels. CSS in styles.less
	// Add the data-label attribute to any textbox or password field
	$('input[type="text"], input[type="password"]').each(function(index){
		if (defined($(this).attr('data-label'))){
			// Add the label and apply styling
			$(this).parent()
				.addClass('field_container')
				.prepend(
					$('<div class="field_label" style="display:' + $(this).css('display') + ';">' + $(this).attr('data-label') + '</div>').click(function(){
						// Fix IE so label click sends focus to field.
						$(this).next().focus();
					})
				);
			
			// CSS display value moved to parent div, we can show the field now.
			$(this).show();
				
			// Keep label hidden on startup if field is not empty
			if ($(this).val() != ''){
				$(this).prev('div.field_label').css('visibility', 'hidden');
			}
				
			// Hide the label on key press
			$(this).keydown(function(event){
				$(this).prev('div.field_label').css('visibility', 'hidden');
			});
			
			// Hide the label on change
			$(this).change(function(event){
				$(this).prev('div.field_label').css('visibility', 'hidden');
			});
			
			// Show the label on blur if the field is empty
			$(this).blur(function(event){
				if ($(this).val() == ''){
					$(this).prev('div.field_label').css('visibility', 'visible');
				}
			});
		}
	});
	
	$('select').change(function(){
		if ($(this).val() == ''){
			$(this).css('color', '');
		} else {
			$(this).css('color', '#000000');
		}
	});

}); // End DOM Ready


