$(window).load(function() {
	var scrollapi;
	initSite();
});

var _submittedonce = false;

function initSite() {
	//alert("initsite");
	//ui
	$('li').button();
	$('#radioset').buttonset();
	$('#radioset').css('visibility', 'visible');
	//interaction
	$('input[name=menu]').click(menuHandler);
	//disable selection of divs
	$('div').each(function(){($(this).attr('unselectable', 'true'))});

	//load first page from hash
	var hash = $.url.attr('anchor');
	var page = 'home';
	page = hash && hash.match(/(about|contact|pvm|pat|iad|demo)/i) ? hash.toLowerCase() : page;
	selectRadio("radio_"+page);
	//init jScrollPane
	var settings = {
		autoReinitialise: 		true,
		autoReinitialiseDelay: 	500,
		showArrows: 			true,
		maintainPosition: 		true
	};
	scrollapi = $('#content').jScrollPane(settings).data('jsp');
	
	loadPage(page);
}

function menuHandler() {
	selectRadio($(this).attr('id')); // e.g. 'radio_pvm'
	setHash($(this).attr('value')); // e.g. 'pvm'
	loadPageFaded($(this).attr('value'));
}
function loadPageFaded(page) {
	_submittedonce = false;
	scrollapi.getContentPane().fadeTo(200, 0, function() {loadPage(page)});	
}
function selectRadio(id) {
	//remove props
	$('label').attr('aria-pressed', 'false');
	$('label').removeClass('ui-state-active');
	//add props to selected radio
	$('label[for='+id+']').attr('aria-pressed', 'true');
	$('label[for='+id+']').addClass('ui-state-active');
}
function setHash(id) {
	window.location.hash = '#'+id;
}

function loadPage(id) {
	var page = './'+id+'.html';
	scrollapi.getContentPane().load(page, onLoadPage);
	//set color
	//colors of the windows in the homepage are changed in the css
	var clr;
	var clrbtn;
	if(id.match(/pat/i)) { //on air workflow
		clr = '#632b8c'; //'#9600ff';
		clrbtn = '#873bbd';
	} else if (id.match(/pvm/i)) {
		clr = '#262161'; //'#d803ff';
		clrbtn = '#332c81';
	} else if (id.match(/iad/i)) {
		clr = '#c51a66'; // '#ff00a8';
		clrbtn = '#ed207b';
	} else if (id.match(/home|contact/i)) {
		clr = '#13a2dc'; // '#ff00a8';
		clrbtn = '#13a2dc';
	} else if (id.match(/demo/i)) {
		clr = '#13a2dc'; // '#ff00a8';
		clrbtn = '#13a2dc';
	} else {
		clr = '#606060'; //grey
		clrbtn = '#808080';
	}
	$('body').css('background-color', clr);
	//change buttons
	$('.ui-state-default').css('color', '#eeeeee');
	$('.ui-state-active').css('color', clrbtn);
}
function onLoadPage(response, status, xhr) {
	if (status == "error") {
		var msg = "Sorry but there was an error: ";
		$("#content").getContentPane().html(msg + xhr.status + " " + xhr.statusText);
	} else {
		//page inits
		//$('button').button();
		//$('#demo-submit').button();
		initHome();
		initDownloadButtons();
		initVideoPopups();
		initVideoPopup2();
		initScrolls();
	}
}
function initScrolls() {
	scrollapi.getContentPane().fadeTo(300, 1);
	scrollapi.reinitialise();
}
function initVideoPopups() {
	//vars
	var ahref = $("a[rel='videopopup']");
	var url = ahref.attr('href');
	var filebase = ahref.attr('filebase');
	
	//rollover images
	var imghtml = '<div style="position:absolute" ><img src="showreel/'+filebase+'.jpg" alt="" width="320" height="180" border="0"/></div>';
	imghtml += '<div style="position:absolute"><img src="graphics/videobutton-off.png" hover="graphics/videobutton-on.png" rel="hover" alt="" width="320" height="180" border="0"/></div>';
//	imghtml += navigator.userAgent.toLowerCase();
	ahref.append(imghtml);
	//rollover interaction
	var img0 = 'graphics/videobutton-off.png';
	var img1 = 'graphics/videobutton-on.png';
	$("img[rel='hover']").hover(function() {
		$(this).attr('temp', $(this).attr('src'));
		$(this).attr('src', $(this).attr('hover'));
	}, function() {
		$(this).attr('src', $(this).attr('temp'));
	});
	
	
	//popups
	var pophtml;
//	if( (($.browser.safari || /firefox\/5.0/.test(navigator.userAgent.toLowerCase()) ) && ! /chrome/.test(navigator.userAgent.toLowerCase()))) {
	if($.browser.safari && ! /chrome/.test(navigator.userAgent.toLowerCase())) {
		pophtml = '<video width="640" height="360" controls autoplay poster="showreel/'+filebase+'.jpg">';
		pophtml += '<source src="'+url+'" type="video/mp4; codecs=\"avc1.42E01E, mp4a.40.2\"">'; 
		pophtml += '</video>';
		ahref.colorbox({iframe:false, scrolling:false, innerWidth:640, innerHeight:360, initialWidth:320, initialHeight:180, html:pophtml});
	} else {
		pophtml = '<object width="640" height="360" type="application/x-shockwave-flash" data="http://automo.tv/nsplayer/nsplayer.swf?file='+url+'&looping=false&hidecontroller=false&autoplay=true">';
		pophtml += '<param name="allowfullscreen" value="true" />';
		pophtml += '<param name="allowscriptaccess" value="always" />';
		pophtml += '<param name="flashvars" value="file='+url+'&looping=false&hidecontroller=false&autoplay=true" />';
		pophtml += '<param name="movie" value="http://automo.tv/nsplayer/nsplayer.swf?file='+url+'&looping=false&hidecontroller=false&autoplay=true" /></object>';
		ahref.colorbox({iframe:false, scrolling:false, innerWidth:640, innerHeight:360, initialWidth:320, initialHeight:180, html:pophtml});
	}
}

function initVideoPopup2() {
	//vars
	var ahref = $("a[rel='videopopup2']");
	var url = ahref.attr('href');
	var filebase = ahref.attr('filebase');
	
	//rollover images
	var imghtml = '<div style="position:absolute" ><img src="showreel/'+filebase+'.jpg" alt="" width="320" height="180" border="0"/></div>';
	imghtml += '<div style="position:absolute"><img src="graphics/videobutton-off.png" hover="graphics/videobutton-on.png" rel="hover" alt="" width="320" height="180" border="0"/></div>';
	ahref.append(imghtml);
	//rollover interaction
	var img0 = 'graphics/videobutton-off.png';
	var img1 = 'graphics/videobutton-on.png';
	$("img[rel='hover']").hover(function() {
		$(this).attr('temp', $(this).attr('src'));
		$(this).attr('src', $(this).attr('hover'));
	}, function() {
		$(this).attr('src', $(this).attr('temp'));
	});
	
	
	//popups
	var pophtml;
	if( ($.browser.safari && ! /chrome/.test(navigator.userAgent.toLowerCase()))) {
		pophtml = '<video width="640" height="360" controls autoplay poster="showreel/'+filebase+'.jpg">';
		pophtml += '<source src="'+url+'" type="video/mp4; codecs=\"avc1.42E01E, mp4a.40.2\"">'; 
		pophtml += '</video>';
		ahref.colorbox({iframe:false, scrolling:false, innerWidth:640, innerHeight:360, initialWidth:320, initialHeight:180, html:pophtml});
	} else {
		pophtml = '<object width="640" height="360" type="application/x-shockwave-flash" data="http://automo.tv/nsplayer/nsplayer.swf?file='+url+'&looping=false&hidecontroller=false&autoplay=true">';
		pophtml += '<param name="allowfullscreen" value="true" />';
		pophtml += '<param name="allowscriptaccess" value="always" />';
		pophtml += '<param name="flashvars" value="file='+url+'&looping=false&hidecontroller=false&autoplay=true" /></object>';
		pophtml += '<param name="movie" value="http://automo.tv/nsplayer/nsplayer.swf?file='+url+'&looping=false&hidecontroller=false&autoplay=true" /></object>';
		ahref.colorbox({iframe:false, scrolling:false, innerWidth:640, innerHeight:360, initialWidth:320, initialHeight:180, html:pophtml});
	}
}
function initDownloadButtons() {
	$('button.download').click(function() {
		//prevent second click
		$(this).click(function() {
			return false;
		});
		var file = $(this).attr('file');
		var busy = $(this).attr('busy');
		if(!busy) {
			//mark as busy
			$(this).attr('busy', 'true');
			//download file
			file = $(this).attr('file');
			//create invisible iframe to download file into
			var el = document.createElement("iframe");
			el.setAttribute('id', 'ifrm');
			el.setAttribute('width', '0px');
			el.setAttribute('height', '0px');
			el.setAttribute('border', '0px');
			document.body.appendChild(el);
			el.setAttribute('src', 'http://automo.tv/'+file);
			//change button
			$(this).html("THANK YOU");
			//remove download class
			//$(this).removeClass("download");
			$(this).fadeTo(400, 0.5);
		} else {
			$(this).html("BUSY");
		}
	});
}



function initHome() {
	$('#pat').click(function() {
		$('input[value=pat]:radio').click();
	});
/*	$('.homewindows .window').hover(function() {
		$(this).animate({
			height: '475px'
		}),
		$(this).animate({
			height: '280px'
		});
	});
	*/
	$('#pvm').click(function() {
		$('input[value=pvm]:radio').click();
	});
	$('#iad').click(function() {
		$('input[value=iad]:radio').click();
	});
}

function submitDemo() {
	//alert('submit demo');
	if(_submittedonce) {
		$('#demo-submit').fadeTo(1500, 0.6);
		$('#demo-submit').val("SENDING");
	} else {
		_submittedonce = true;
		var firstname = $('#firstname').val();
		if(!firstname) {
			$('#firstname').addClass('error');
			$('#firstname').change(function(){$(this).removeClass('error')})
		} else {
			$('#firstname').removeClass('error');
		}
		var mobile = $('#mobilephone').val();
		mobile = mobile.replace(/[^\d\+,]/g, ""); //filter all non digits, except + and , (for multiple entries)	
		$('#mobilephone').val(mobile);
		if(!mobile || mobile.length < 10) {
			$('#mobilephone').addClass('error');
			$('#mobilephone').change(function(){$(this).removeClass('error')})
		} else {
			$('#mobilephone').removeClass('error');
		}
	
		if(mobile && mobile.length >= 10 && firstname) {
				//alert("submit: "+firstname+" mobile:"+mobile);
				$('#demo-submit').hide();
				$('.submitloadbar').fadeTo(1500, 0.6);
				$('#mobilephone').fadeTo(1500, 0.4);
				$('#firstname').fadeTo(1500, 0.4);
				submitAutomo(mobile, firstname);
				//submitSuccessHandler();
		}
	}
}

function submitAutomo(mymobile, myfirstname) {
//	$.get("http://demo.automo.tv/flash/index.php", { mode: "flashsubmit", mobile: mymobile, firstname: myfirstname }, submitHandler);
//	$.ajax({  
//	  type: "POST",
//	  url: "http://demo.automo.tv/flash/?",
//	  data: {mode: 'flashsubmit', mobile: mymobile, firstname: myfirstname},
//	  success: submitHandler
//	});
	var targetUrl = "http://automo.tv/cgi-bin/pvm.php";
	var parameters = {mode: 'flashsubmit', mobile: mymobile, firstname: myfirstname };
	$.ajax({    
	  type: "GET",
	  async: true,
	  url: targetUrl,
	  data: parameters,
	  success: submitHandler
	});
}
function submitHandler(response, status, xhr) {
	$('#mobilephone').attr("disabled", true);
	$('#firstname').attr("disabled", true); 
	$('.submitloadbar').hide();
	if (status == "error") {
	//	var msg = "<h1>Sorry</h1>there was an error: ";
	//	$('#demo-info').html(msg + xhr.status + " text:" + xhr.statusText + " response:"+$(response).find("result").text());
	} else {
		$('#demo-info').append("<h1>Your PVM will be sent shortly</h1>");
	//	$('#demo-info').append("status:"+xhr.status + " text:" + xhr.statusText + " response:" + $(response).find("result").text() + " status:"+status);
		$('.demo-footnote-window').fadeTo(1500, 1);
	}
}


