var http_request = false;
function makeRequest(url, parameters, callback) {
	http_request = false;
    if (window.XMLHttpRequest) {
    	http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
        	http_request.overrideMimeType('text/html');
        }
    } 
    else if (window.ActiveXObject) { // IE
    	try {
    		http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } 
    	catch (e) {
    		try {
    			http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } 
    		catch (e) {}
        }
    }
    if (!http_request) {
    	return false;
    }
    http_request.onreadystatechange = callback;
    http_request.open('POST', url, true);
    http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http_request.setRequestHeader("Content-length", parameters.length);
    http_request.setRequestHeader("Connection", "close");
    http_request.send(parameters);
}

function changeClassName(arg, state){
	var theClassName = state=='on' ? 'leftMenuSelected' : 'leftMenuUnselected';
	var li = 'menuLi' + arg;
	$(li).className = theClassName;
}

function login(){
	var username = $('username').value;
	var password = $('password').value;
	if(username == '' || password == ''){
		$('loginError').className = 'visible';
		return;
	}
	document.getElementById('loginForm').submit();
}

function isEmpty(value){
	return value == '';
}

function invalidMail(email){
	var dotFound = false;
	var atFound = false;
	for(i=0;i<email.length;i++){
		if(email.charAt(i) == '@'){
			atFound = true;
		}
		if(email.charAt(i) == '.'){
			dotFound = true;
		}
	}
	return !dotFound || !atFound;
}

function prepareSearch(){
	var searchField = escape($('searchField').value);
	//alert(searchField);
	if(!isEmpty(searchField)){
		var url = "/search/" + escape(searchField);
		window.location.href = url;
	}
}

function sortList(){
	var sort= $('sort').value;
	var sortingURL= $('sortingURL').value;
	location.href = sortingURL + sort;
}

function checkKeyPress(evt, caller){
	var keyCode;
	if( evt.which ) {
		keyCode = evt.which;
	} 
	else if( evt.keyCode ) {
		keyCode = evt.keyCode;
	}
	if(keyCode == 13){
		if(caller == 'search'){
			var searchField = escape($('searchField').value);
			alert(searchField);
			if(!isEmpty(searchField)){
				var url = "http://localhost/search/" + escape(searchField);
				window.location.href = "http://www.google.se";
			} 
		}
	}
}

function checkEnter(event){
	if (window.event && window.event.keyCode == 13) {
		event.returnValue = false;
		//alert("uno");
		var searchField = escape($('searchField').value);
		//alert(searchField);
		if(!isEmpty(searchField)){
			var url = "/search/" + escape(searchField);
			location.href = url;
		}
		//location.href = "http://www.google.se";
		prepareSearch();
	} 
	else if (event && event.keyCode == 13) {
		event.preventDefault();
		//alert("ao");
		//location.href = "http://www.gazzetta.it";
		var searchField = escape($('searchField').value);
		//alert(searchField);
		if(!isEmpty(searchField)){
			var url = "/search/" + escape(searchField);
			window.location.href = url;
		}
		prepareSearch();
	}
}

function checkLogin(event){
	if (window.event && window.event.keyCode == 13) {
		//alert("uno");
		event.returnValue = false;
		//location.href = "http://www.google.se";
		login();
	} 
	else if (event && event.keyCode == 13) {
		event.preventDefault();
		//alert("ao");
		//location.href = "http://www.gazzetta.it";
		login();
	}
}

function supportQuestion(q){
	var img_id = 'support_img_' + q;
	if($(q).style.display == 'block'){
		$(q).style.display = 'none';
		$(img_id).src = 'http://ss55i01.stream.ip-only.net/img/public/icon_bullet_down.gif';
	}
	else{
		$(q).style.display = 'block';
		$(img_id).src = 'http://ss55i01.stream.ip-only.net/img/public/icon_bullet_up.gif';
	}
}

function rateMovie(stars, movie_id, loggedIn){
	stars = parseInt(stars) + 1;
	var args = "stars=" + encodeURI( stars ) +"&movie_id=" + encodeURI( movie_id );
	makeRequest("/process/rate.php", args, ratingResponse);
}

function rgmlInfo(){
	var obj = document.getElementById('rgml');
	var rgml = obj.GetSystemInfo();
	var args = "rgml=" + encodeURI( rgml );
	//document.getElementById('testalf').value = args;
	makeRequest("/process/drmInfo.php", args, drmResponse);
}

var objStar;
ratingSent = false;
function starHover(id, mode){   
    for (var i = 0; i <= id;i++){        
        objStar = document.getElementById(i);
		if (mode == "on" && !ratingSent)
        	objStar.src = "http://ss55i01.stream.ip-only.net/img/public/icon_starblueondarkgray.gif"
        else if (!ratingSent)
            objStar.src = "http://ss55i01.stream.ip-only.net/img/public/icon_stargrayondarkgray.gif"
    }
}


function drmResponse() {
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			var result = http_request.responseText;
			var obj = document.getElementById('rgml');
			alert('before11');
			try{
				if(result != ''){
					obj.StoreLicense(result);
					alert('prova if');
				}
				else{
					alert('prova else');
				}
				
			}
			catch(e){
				alert('errore');
			}
			alert('end');
		} 
		else {
			alert('There was a problem with the request.');
		}
	}
}

function ratingResponse() {
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			var result = http_request.responseText;
			if(result == 0){
				alert("Something went wrong!");
			}
			else{
				var fullstars = parseInt(result.charAt(0));
				var hafstars = parseInt(result.charAt(1));
				var emptystars = parseInt(result.charAt(2));
				var startsHTML = "<strong>Rating:</strong><br>";
				for(i=0;i<fullstars;i++){
					startsHTML += '<img src="http://ss55i01.stream.ip-only.net/img/public/icon_starblueondarkgray.gif" />&nbsp;';
				}
				for(i=0;i<hafstars;i++){
					startsHTML += '<img src="http://ss55i01.stream.ip-only.net/img/public/icon_starhalfondarkgray.gif" />&nbsp;';
				}
				for(i=0;i<emptystars;i++){
					startsHTML += '<img src="http://ss55i01.stream.ip-only.net/img/public/icon_stargrayondarkgray.gif" />&nbsp;';
				}
				document.getElementById('ratingPostId').innerHTML = startsHTML;
			}
		} 
		else {
			alert('There was a problem with the request.');
		}
	}
}

function validateBuyCredits(){
	var amountCredits = '0';
	if(document.getElementById('credits1').checked){
		amountCredits = '10';
	}
	else if(document.getElementById('credits2').checked){
		amountCredits = '25';
	}
	else if(document.getElementById('credits3').checked){
		amountCredits = '50';
	}
	else{
		if(
			document.getElementById('amount').value == ''  ||
			isNaN(document.getElementById('amount').value)
		){
			alert("Wrong amount");
			return;
		}
		else{
			amountCredits = document.getElementById('amount').value;
		}
	}
	document.getElementById('creditsToBuy').value = amountCredits;
	document.getElementById('buyCreditsForm').submit();
}
function showHideDiv(inid, showhide)
{
    var flipper = document.getElementById(inid);
    if(!showhide)
    	flipper.style.display = "none";
    else
    	flipper.style.display = "block";
}

function addToCart(id, type, upordown, pagetype){
	/*
		var browserOk = BrowserDetect.browser == 'Explorer' ? true : false;
		var osOk = BrowserDetect.OS == 'Windows' ? true : false;
		var isClientOkForDownload = (browserOk && osOk) ? true : false;
	*/
	//if(isClientOkForDownload || type != 1){
		args = "id=" + encodeURI( id ) +"&type=" + encodeURI( type )+"&page_type=" + encodeURI( pagetype )+"&del_or_add=" + encodeURI( upordown );
		if(pagetype=="tinyone")
			makeRequest("/process/addToCart.php", args,cartResponseTiny);
		else
			makeRequest("/process/addToCart.php", args,cartResponse);
	/*}
	else{
		alert("Internet Explorer and Windows are required for buying movies.");
	}*/
} 

function cartResponse() {
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			var result = http_request.responseText;
			document.getElementById('thecart').innerHTML = result;
		} 
		else {
			alert('There was a problem with the request.');
		}
	}
}

function cartResponseTiny() {
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			var result = http_request.responseText;
			document.getElementById('cart').innerHTML = result;
		} 
		else {
			alert('There was a problem with the request.');
		}
	}
}

function streamTimeRegister(stats_unique_num, minute, movie_title_id, stream_type)   
{   
	args = "id=" + encodeURI( movie_title_id ) +"&min=" + encodeURI( minute )+"&uid=" + encodeURI( stats_unique_num )+"&stream_type=" + encodeURI( stream_type );
	makeRequest("/process/streamTimeRegister.php", args,streamTimeRegisterResponce);
	//alert(stats_unique_num+"\n"+minute+"\n"+movie_title_id);
} 

function streamTimeRegisterResponce() {
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			//alert(http_request.responseText);
		} 
		else {
			//alert('Stats problems let Kallio know...');
		}
	}
}

function loadBanner(banner,href){
    // add code here to place banner on page 
    // and add link to it. 
    // "banner" - the URL of the banner ad image
    // "href" - the click-thru URL 
    //alert("platform a ad");
    var bannerIMG = banner;
    var clickThruHref = href;
var bannerLower = bannerIMG.toLowerCase();
var bannerHTML = bannerIMG;
    if ("" == clickThruHref || "DHTML" == clickThruHref || "null" == clickThruHref || 0 < bannerLower.indexOf(".swf") || 0 < bannerLower.indexOf(".html")) {
                bannerHTML = '<HTML><IFRAME id="myiframe" name="myiframe_name" src="' + bannerIMG + '" frameborder="0" scrolling="no" width="300" height="250" marginwidth="0" marginheight="0"/></HTML>';
    } else if (0 == bannerHTML.indexOf("http")) {
      bannerHTML = '<HTML><CENTER><A HREF="' + clickThruHref + '" target="_blank"><IMG SRC="' + bannerIMG + '" border="0"></A></CENTER></HTML>';                       
    } else {
      bannerHTML = '<HTML>' + bannerIMG + '</HTML>';
    }
    var oDiv = document.getElementById("lcBannerDiv");
    oDiv.innerHTML = bannerHTML;



}


function changePaymentMethod(method, isAuthenticated){
    var cred_price = document.getElementById("total_price_creditcard");
    var price = document.getElementById("total_price"); 
	if(method == 'credits'){
		$('enterEmailCreditCard').style.display = 'none';
	    cred_price.style.display='none';
	    price.style.display='inline';
		if(isAuthenticated){
			if($('payWithCreditsDiv')){
				$('payWithCreditsDiv').style.display = "block";
			}
			if($('payWithCreditsText')){
				$('payWithCreditsText').style.display = "block";
			}
		}
		else{
			$('loginForPaymentMethodCredits').style.display = "block";
		}
	}
	else{
		if(method == 'cc' || method == 'pp'){
			cred_price.style.display='inline';
			price.style.display='none';
		}
		else{
			cred_price.style.display='none';
			price.style.display='inline';
		}
		$('enterEmailCreditCard').style.display = 'block';
		if(isAuthenticated){
			if($('payWithCreditsDiv')){
				$('payWithCreditsDiv').style.display = "none";
			}
			if($('payWithCreditsText')){
				$('payWithCreditsText').style.display = "none";
			}
		}
		else{
			if($('loginForPaymentMethodCredits')){
				$('loginForPaymentMethodCredits').style.display = "none";
			}
		}
	}
}

var sentToPaymentClicked = false;

function sendToPaymentPage(isExternabiz){
	if(!sentToPaymentClicked){
		if(!$('terms').checked){
			alert("You must accept the terms of purchase");
			return;
		}

		var confirmation_email = $('confirmation_email').value;
		if(confirmation_email == '' || invalidMail(confirmation_email)){
			alert("You must provide us with a valid email address");
			return;
		}
		
		var validateShippingAddress = $('validateShippingAddress').value;
		var shippingArgs = "";
		if(validateShippingAddress == '1'){
			var name = $('name').value;
			var address = $('address').value;
			var town = $('town').value;
			var zipcode = $('zipcode').value;
			var country = $('country').value;
			var address2 = $('address2').value;
			var state = $('state').value;
			var phone = $('phone').value;
			
			shippingArgs = "&name=" + encodeURI(name);
			shippingArgs += "&address=" + encodeURI(address);
			shippingArgs += "&town=" + encodeURI(town);
			shippingArgs += "&zipcode=" + encodeURI(zipcode);
			shippingArgs += "&country=" + encodeURI(country);
			shippingArgs += "&address2=" + encodeURI(address2);
			shippingArgs += "&state=" + encodeURI(state);
			shippingArgs += "&phone=" + encodeURI(phone);
			
			if(name == ''){
				alert("You must enter your name");
				return;
			}
			
			if(address == ''){
				alert("You must enter your address");
				return;
			}
			
			if(town == ''){
				alert("You must enter your city");
				return;
			}
			
			if(zipcode == ''){
				alert("You must enter your zip code");
				return;
			}
			
			if(country == '0'){
				alert("You must enter your country");
				return;
			}
			
		}
		
		var newletters = "0";
		if($('newletters').checked){
			newletters = "1";
		}
		
		//Here we can redirect the user directly to the payment page.
		if($('payment_method_cc').checked){
			sentToPaymentClicked = true;
			if(isExternabiz){
				top.location.href = "/process/preparePaypal.php?type=cash&amount=0&confirmation_email=" + confirmation_email + "&newletters=" + newletters + shippingArgs;
			}
			else
			location.href = "/process/preparePaypal.php?type=cash&amount=0&confirmation_email=" + confirmation_email + "&newletters=" + newletters + shippingArgs;
		}
		else if($('payment_method_pp').checked){
			sentToPaymentClicked = true;
			if(isExternabiz){
				top.location.href = "/process/preparePaypal.php?type=paypal&amount=0&confirmation_email=" + confirmation_email + "&newletters=" + newletters + shippingArgs;
			}
			else
				location.href = "/process/preparePaypal.php?type=paypal&amount=0&confirmation_email=" + confirmation_email + "&newletters=" + newletters + shippingArgs;
		}
		//Here we need to understand the user choise before sending him to the payment page.
		else if($('payment_method_credits').checked){
			var userIsAuthenticated = $('userIsAuthenticated').value;
			if(userIsAuthenticated=='0'){
				alert("You must login in order to buy the movie with credits");
			}
			else{
				var payWithCreditsOk = $('payWithCreditsOk').value;
				if(payWithCreditsOk=='1'){
					sentToPaymentClicked = true;
					location.href = "/process/payWithCredits.php?confirmation_email=" + confirmation_email + shippingArgs;
				}
				else{
					if($('buy100').checked){
						sentToPaymentClicked = true;
						location.href = "/process/preparePaypal.php?type=credits&amount=100" + shippingArgs;
					}
					else if($('buy50').checked){
						sentToPaymentClicked = true;
						location.href = "/process/preparePaypal.php?type=credits&amount=50" + shippingArgs;
					}
					else if($('buy25').checked){
						sentToPaymentClicked = true;
						location.href = "/process/preparePaypal.php?type=credits&amount=25" + shippingArgs;
					}
					else if($('buy10').checked){
						sentToPaymentClicked = true;
						location.href = "/process/preparePaypal.php?type=credits&amount=10" + shippingArgs;
					}
					else{
						var minimunCreditsToBuy = $('minimunCreditsToBuy').value;
						var creditsToBuy = $('creditsToBuy').value;
						if(isNaN(creditsToBuy)){
							alert("You must enter the amount of credits you want to buy, at least " + minimunCreditsToBuy);
							return;
						}
						if(parseInt(creditsToBuy) < parseInt(minimunCreditsToBuy)){
							alert("You must enter the amount of credits you want to buy, at least " + minimunCreditsToBuy);
							return;
						}
						else{
							sentToPaymentClicked = true;
							location.href = "/process/preparePaypal.php?type=credits&amount=" + creditsToBuy + shippingArgs;
						}
					}
				}
			}
		}
		else{
			alert("You must select a payment method");
		}
		
	}
	
}

function goToFromCheckout(id){
	//$(id).submit();
	if(id == "passwordFromCheckout")
		location.href="/member/password";
	else if(id == "registerFromCheckout")
		location.href="/member/registration";
}

function deselectButton(id){
	$(id).checked = false;
	if($(id).checked){
		alert("checked");
	}
	else{
		alert("not checked");	
	}
}

function makeRadioToggleGroup(group){
	if(group.length){
		for(var i=0, len=group.length; i<len; i++){
			group[i].lastState=group[i].checked;  
			group[i].onclick=(function(g, b){return function(){btoggle(g, b);}})(group, group[i]);
		} 
	}
	else{
		group.lastState=group.checked;  
		group.onclick=function(){
			if(this.lastState)
				this.checked=false;
			this.lastState=this.checked;
		}
	}
}
	function btoggle(set, btn){
		if(btn.lastState==true)
			btn.checked=false;
		for(var i=0; i<set.length; i++)
			if(set[i] != btn) 
				set[i].lastState=false;
		btn.lastState=btn.checked;       
	}


	var download_movie_filename = "";
	var download_movie_id = "";
	var download_web_orders_details_id = '';
	var download_counter = '';
	var package_order_id  = '';
	
	function checkInstallLicense(movie_id, key_code, movie_filename, web_orders_details_id, counter){
		var installButton = 'installButton' + counter;
		$(installButton).value = "Installing license";
		$(installButton).disabled = true;
		download_movie_filename = movie_filename;
		download_movie_id = movie_id;
		download_web_orders_details_id = web_orders_details_id;
		download_counter = counter;
		var args = '?movie_id=' + movie_id + '&key_code=' + key_code;
		makeRequest("/process/checkInstallLicense.php" + args, '', checkInstallLicenseResponse);
	}
	
	function checkInstallLicensePackage(movie_id, key_code, movie_filename, pkg_order_id, counter){
		var installButton = 'installButton' + counter;
		$(installButton).value = "Installing license";
		$(installButton).disabled = true;
		download_movie_filename = movie_filename;
		download_movie_id = movie_id;
		package_order_id = pkg_order_id;
		download_counter = counter;
		installLicensePackage(package_order_id, download_movie_id, download_counter)
	}
	
	
	
	function checkInstallLicenseResponse(){
		if (http_request.readyState == 4) {
			if (http_request.status == 200) {
				var result = http_request.responseText;
				if(result != '0'){
					if(result == 'INSTALL'){
						installLicense(download_web_orders_details_id, download_movie_id, download_counter)
					}
				}
			} 
			else {
				alert('There was a problem with the request.');
			}
		}	
	}
	
	
	function downloadMovie(){
		document.getElementById('iframeMovie').src = 'http://ss55i01.stream.ip-only.net/' + download_movie_filename;
		var downloadMovieId = 'downloadMovieId' + download_movie_id;
		document.getElementById(downloadMovieId).innerHTML = "Downloaded";
	}

