/* Maxdriving Javascript */
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_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_findObj(n, d) { //v4.01
  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);
  if(!x && d.getElementById) x=d.getElementById(n);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];}
}

// Class to language translation usin JSON syntax by ljimenez
var mLang = {
	variable: new Array(),
	translation: new Array(),
	addTranslation: function(varname, text){
		this.variable[this.variable.length] = varname;
		this.translation[this.translation.length] = text;
	},
	getTranslation: function(varname){
		text = '';
		for (i=0; i < this.variable.length; i++){
			if (this.variable[i] == varname){
				text = this.translation[i];
				break;
			}
		}
		return text;
	}
}

var mWindow = {
	full: true,
	Change: function(){
    $('#fullscreenDialog').dialog({autoOpen: false,
			dialogCLass: 'info',
			draggable: false,
			resizable: false,
			bgiframe: true,
			modal: true,
			zindex: 2000,
			buttons: {
				'Ok': function() {
					$(this).dialog('close');
				}
			}
		});
    $('#fullscreenDialog').dialog('open');
	}
}

var mPlayer = {
	iReputation: 0,
	iMoney: 0,
	iCredits: 0, 
	Setup: function(iReputation, iMoney,  iCredits){
		this.iReputation = iReputation;
		this.iMoney = iMoney;
		this.iCredits = iCredits;
	},
	setHTML: function(reputation, money, credits, msg){
		$('#dlg_msg').remove();
		$('#logo .reputation').html(reputation);
		$('#logo .money').html(money);
		$('#logo .credits').html(credits);
		$('#logo').prepend(msg);
//		$('#dlg_msg').fadeIn('slow');
		$(document).ready(function() 
		{
			$('#dlg_msg').show("slide", {direction: "up"}, 1000);
			setTimeout('$(\'#dlg_msg\').fadeOut(\'slow\');', 10*1000); // 10 seconds	
		});		
	},
	getReputation: function (){
		return this.iReputation;
	},
	getMoney: function(){
		return this.iMoney;
	},	
	getCredits: function(){
		return this.iCredits;
	},
	getCreditsToMoney: function(){
		return this.iCredits*100;
	}
}


function mRoot(logged, dlg_msg, indexSelected){
	//$('.tooltip').tipTip({maxWidth: "300px", edgeOffset: 10, delay:100, defaultPosition: "top"});
  $('.tooltip').tipTip({maxWidth: "300px", edgeOffset: 1, delay:100, defaultPosition: "top"});
	// checking user is looged
	if (logged == true){
		$('#dlg_msg').hide();
		// checking if we need to show message
		if (dlg_msg == true){
//				$('#dlg_msg').fadeIn('slow');
				$(document).ready(function() 
				{
					$('#dlg_msg').show("slide", {direction: "up"}, 1000);
					setTimeout('$(\'#dlg_msg\').fadeOut(\'slow\');', 10*1000); // 10 seconds	
				});				
		}

		// load logout
		$("#logoutDialog").bgiframe();
		$("#logoutDialog").dialog({
			autoOpen: false,
			dialogCLass: 'info',
			draggable: false,
			resizable: false,
			bgiframe: true,
			modal: true,
			zindex: 2000,
			buttons: {
				'Exit': function() {
					window.location.replace('index.php?a=810');
				},
				'Cancel': function() {
					$(this).dialog('close');
				}
			}
		});

		// load help dialog
		$('#help').hide();
		$('#help').css('position','absolute');
		$('#help').css('top', ( $(window).height() - $('#help').height() ) / 2+$(window).scrollTop() + 'px');
		$('#help').css('left', ( $(window).width() - $('#help').width() ) / 2+$(window).scrollLeft() + 'px');
		$('#help').css('z-index', 1000);
		$('#help').bgiframe();

		// menu naviagation
//		var navAPI = $("#nav").scrollable({items: "#nav_subs",
//			size: 1,
//			keyboard: false,
//			clickable: true,
//			onBeforeSeek: function(event,index) {
//				$("#nav_main").css("z-index",666);
//			},
//			onSeek: function() {
//				$("#nav_main").css("z-index","auto");
//			}
//    }).navigator({api: true, navi: "#nav_main"});
//    navAPI.setPage(indexSelected);
  	$('.nav_sub').get(indexSelected).style.display='block';

		// main menu
		$("#nav_main_9").click(function (){mHelp(true);});
	}
  $("#contactDialog").bgiframe();
  $("#contactDialog").dialog({
		autoOpen: false,
		dialogCLass: 'info',
		bgiframe: true,
		draggable: false,
		resizable: false,
		modal: true,
		width: 400,
		zindex: 2000,
		buttons: {
			'Send': function() {
				$.post(mURL+'pages/welcome/contact/action.php',
					{cName: $('.cName').val(), cType: $('.cType option:selected').val(), cEmail: $('.cEmail').val(), cMessage:$('.cMessage').val()},
					function(){$("#contactDialog").dialog('close');}
				);
			}
		},
		open: function() {
			$('#contactDialog').load(mURL+'pages/welcome/contact/index.htm');
		}
	});
}

function mHelp(bOpen){
  if($('#help .contenido').html()!='Help no available.'){
    if (bOpen == true){
			$('#help').fadeIn('slow');
			fleXenv.fleXcrollMain('flexhelp');
		}
    else $('#help').fadeOut('slow');
	}
}

// load login script
function mLoginUp(){
	$('#loginForm').keypress(function(event) {
  	if (event.keyCode == '13')	$('#loginForm').submit();
	});

	// Forgot Password
	$('#dlg_forgot_password').hide();
	$('#dlg_forgot_password').dialog({autoOpen: false, 
		dialogCLass: 'info',
		draggable: false,
		resizable: false,
		bgiframe: true,
		modal: true
	});
	
	// Incorrect login
	$('#dlg_incorrect_login').hide();
	$('#dlg_incorrect_login').dialog({autoOpen: false, 
		dialogCLass: 'info',
		draggable: false,
		resizable: false,
		bgiframe: true,
		modal: true,
		buttons: {"Ok": function() {$(this).dialog("close");}}
	});
	
	// User Inactive
	$('#dlg_user_inactive').hide();
	$('#dlg_user_inactive').dialog({autoOpen: false, 
		dialogCLass: 'info',
		draggable: false,
		resizable: false,
		bgiframe: true,
		modal: true
	});
	
	// Emails Sent
	$('#dlg_sent_reset_password_link').hide();
	$('#dlg_sent_reset_password_link').dialog({autoOpen: false, 
		dialogCLass: 'info',
		draggable: false,
		resizable: false,
		bgiframe: true,
		modal: true
	});
	
	$('#dlg_sent_activation_link').hide();
	$('#dlg_sent_activation_link').dialog({autoOpen: false, 
		dialogCLass: 'info',
		draggable: false,
		resizable: false,
		bgiframe: true,
		modal: true
	});
}

function mNewPasswordUp(){
	$('#dlg_error_password_short').hide();
	$('#dlg_error_password_short').dialog({autoOpen: false, 
		dialogCLass: 'info',
		draggable: false,
		resizable: false,
		bgiframe: true,
		modal: true
	});
	
	$('#dlg_error_password_match').hide();
	$('#dlg_error_password_match').dialog({autoOpen: false, 
		dialogCLass: 'info',
		draggable: false,
		resizable: false,
		bgiframe: true,
		modal: true
	});
	
	$('#frmNewPassword').submit(function() {
		$('#passwordFieldA').val( trim($('#passwordFieldA').val()) );
		$('#passwordFieldB').val( trim($('#passwordFieldB').val()) );
		
		//We check the password typo and stop the sent if it doesn't match
		if( $('#passwordFieldA').val() == $('#passwordFieldB').val() ) {
			//We check the password lenght and stop if < 5 characters
			if ($('#passwordFieldA').val().length > 4) {
				//the hash is calculated
				$('#passwordHash').val($('#passwordFieldA').val());
				
				//the password fields are cleared so they send blank
				$('#passwordFieldA').val('');
				$('#passwordFieldB').val('');
				
				return true;
			}
			else {
				//ERROR SHOWN
				$('#dlg_error_password_short').dialog('open');
				
				return false;
			}
		}
		else {
			//ERROR SHOWN
			$('#dlg_error_password_match').dialog('open');
					
			return false;
		}
		
		return false;
	});
}

// Office Driver
function mDriverUp(){
	// dialogs
	$("#dlg_sell").dialog({
    autoOpen: false,
		resizable: false,
    draggable: false,
		modal: true,
		buttons: {
			'Yes': function() {
				$(this).dialog('close');
				window.location.href = $('#sell').attr('href');
			},
			'No': function() { 
				$(this).dialog('close');
			}
		}
  });
	$("#dlg_arrested").dialog({
    autoOpen: false,
		resizable: false,
    draggable: false,
		modal: true,
		buttons: {
			'Yes': function() {
				$(this).dialog('close');
				window.location.href = $('#arrested').attr('href');
			},
			'No': function() { 
				$(this).dialog('close');
			}
		}
  });
	$("#dlg_injured").dialog({
    autoOpen: false,
		resizable: false,
    draggable: false,
		modal: true,
		buttons: {
			'Yes': function() {
				$(this).dialog('close');
				window.location.href = $('#injured').attr('href');
			},
			'No': function() { 
				$(this).dialog('close');
			}
		}
  });
}

// Main garage -->>
function mGarageUp(CarImage){
	// garage start
	$('#mGarage').children().hide();
	$('#mGarage_CAR_INFO').show();
	$('#mCarPart').children().hide();
	
	// dialogs
	$("#dlg_sell").dialog({
    autoOpen: false,
		resizable: false,
    draggable: false,
		modal: true,
		buttons: {
			'Yes': function() {
				$(this).dialog('close');
				window.location.href = $('#sell').attr('href');
			},
			'No': function() { 
				$(this).dialog('close');
			}
		}
  });
	$("#dlg_arrested").dialog({
    autoOpen: false,
		resizable: false,
    draggable: false,
		modal: true,
		buttons: {
			'Yes': function() {
				$(this).dialog('close');
				window.location.href = $('#arrested').attr('href');
			},
			'No': function() { 
				$(this).dialog('close');
			}
		}
  });
	$("#dlg_injured").dialog({
    autoOpen: false,
		resizable: false,
    draggable: false,
		modal: true,
		buttons: {
			'Yes': function() {
				$(this).dialog('close');
				window.location.href = $('#injured').attr('href');
			},
			'No': function() { 
				$(this).dialog('close');
			}
		}
  });
	//MM_swapImage('CarImage','',CarImage,1);
	$('#CarImage').attr('src', CarImage);
}

function mContainer_ViewPart(container, part){
	/*$('#'+container).children().hide();
	$('#'+container+'_'+part).show();*/
	$('#'+container).children().hide().fadeOut('slow');
	$('#'+container+'_'+part).fadeIn('slow');
	if (part == 'SELECT_CAR') fleXenv.fleXcrollMain('flexlistcar');
}

/*
function mShowMaps(aXML, aMapDiv, i){
	//alert(aXML.length);
	if (i < aXML.length){
		// new track is neccesary
		if (!track || track.fileXML != aXML[i]) track = new Track(aXML[i]);
		if (track.isReady){
			oTrackMap = new GMap2(document.getElementById(aMapDiv[i]), {size:new GSize(parseInt($('#'+aMapDiv[i]).css('width')),parseInt($('#'+aMapDiv[i]).css('height')))});
			oTrackMap.setMapType(G_SATELLITE_MAP); //G_SATELLITE_MAP G_NORMAL_MAP
			track.optimizeForMap(oTrackMap); // Optimize Map one time
			oTrackMap.setCenter(track.center,track.zoom);
			oTrackMap.clearOverlays();
			oTrackMap.addOverlay(track.route);
			oTrackMap.disableDragging();
			oTrackMap.disableDoubleClickZoom();
			oTrackMap.disableContinuousZoom();
			oTrackMap.disableScrollWheelZoom();
			if(track.isClose) {
				oTrackMap.addOverlay(track.startFinish);
			} else {
				oTrackMap.addOverlay(track.start);
				oTrackMap.addOverlay(track.finish);
			}
			i++;
			track = null;
			mShowMaps(aXML, aMapDiv, i);
		}
		else {
			//alert('timeout'+i);
			setTimeout('mShowMaps(["'+aXML.join('","')+'"],["'+aMapDiv.join('","')+'"],'+i+')', 1000);
		}
	}
}

function mSetCarColor(id, value){
	$('img[id|='+id.substring(0,4)+'_1]').css('border','2px solid transparent');
	$('img[id|='+id.substring(0,4)+'_2]').css('border','2px solid transparent');
	$('#'+id).css('border','2px solid #00FF00');
	$('#carcolor').val(value);
}*/

// Active races -->>
function mActiveRacesUp(aseconds){
	$('#race_blocked').dialog({autoOpen: false, modal: true, hide: 'blind', draggable: false, resizable: false});
	$('#race_started').dialog({autoOpen: false, modal: true, hide: 'blind', draggable: false, resizable: false});
	// cheking are array
	if (typeof(aseconds) == 'object' && aseconds.length){
		for(i=0; i < aseconds.length; i++){
			setListRaceOnclick('row_'+i, aseconds[i]);
		}
	}
}

function setListRaceOnclick(row, status){
	//alert(status);
	switch(status){
		case 'finished':
			$('#'+row).click(function() {window.location.href = '../finished/';});
			break;	
		case 'start':
			$('#'+row).attr('onclick','');
			$('#'+row).click(function() { 
				$('#race_blocked').dialog('close');
				$('#race_started').dialog({modal: true, hide: 'blind', draggable: false, resizable: false});
				$('#race_started').dialog('open');
			});
			setTimeout('setListRaceOnclick("'+row+'","finished")', 2*60*1000); // running for 2 minutes
			break;
		case 'block':
			$('#'+row).attr('onclick','');
			$('#'+row).click(function() { 
				$('#race_started').dialog('close');
				$('#race_blocked').dialog({modal: true, hide: 'blind', draggable: false, resizable: false});
				$('#race_blocked').dialog('open');
			});
			setTimeout('setListRaceOnclick("'+row+'","start")', 5*60*1000); // block last 5 minutes
			break;
		default:
			// status = rest seconds
			rest = status - 5*60 - 3; // including error
			if (rest < 0){
				$('#'+row).attr('onclick','');
				$('#'+row).click(function() { 
					$('#race_blocked').dialog({modal: true, hide: 'blind', draggable: false, resizable: false});
					$('#race_blocked').dialog('open');
				});
				setTimeout('setListRaceOnclick("'+row+'","start")', status*1000);
			}
			else	setTimeout('setListRaceOnclick("'+row+'","block")', rest*1000);
			break;
	}
}

function mEditRaceUp(status){
	//alert(status);
	switch(status){
		case 'finished':
			$('#timerflash').click(function() {window.location.href = '../../finished/';});
			break;	
		case 'start':
			$('#abandon').hide();
			$('.bigbutton').hide();
			$('.actionbutton').html($('#race_started').html());
			$('#timerflash').click(function() {window.location.href = '../';});
			setTimeout('mEditRaceUp("finished")', 2*60*1000); // running for 2 minutes
			break;
		case 'block':
			$('#abandon').hide();
			$('.bigbutton').hide();
			$('.actionbutton').html($('#race_blocked').html());
			$('#timerflash').click(function() {window.location.href = '../';});
			setTimeout('mEditRaceUp("start")', 5*60*1000); // block last 5 minutes
			break;
		default:
			// abandone dialoge
			$("#dlg_abandon").dialog({
        autoOpen: false,
				resizable: false,
        draggable: false,
				modal: true,
				buttons: {
					'Yes': function() {
						$(this).dialog('close');
						window.location.href = $('#abandon').attr('href');
					},
					'No': function() { 
						$(this).dialog('close');
					}
				}
			});		
			// status = rest seconds
			rest = status - 5*60; // including error
			if (rest < 0){
				$('.bigbutton').hide();
				$('.actionbutton').html($('#race_blocked').html());
				$('#timerflash').click(function() {window.location.href = '../';});
				setTimeout('mEditRaceUp("start")', status*1000);
			}
			else	setTimeout('mEditRaceUp("block")', rest*1000);
			break;
	}
}
/*
function mFinishedRacesUp(){
	$("#dlg_driver_arrested").dialog({autoOpen: false,
		resizable: false,
		modal: true,
		buttons: {
			'Yes': function() {
				$(this).dialog('close');
				window.location.href = $('#driver_arrested').attr('href');
			},
			'No': function() { 
				$(this).dialog('close');
			}
		}
  });
	$("#dlg_driver_injured").dialog({autoOpen: false,
		resizable: false,
		modal: true,
		buttons: {
			'Yes': function() {
				$(this).dialog('close');
				window.location.href = $('#driver_injured').attr('href');
			},
			'No': function() { 
				$(this).dialog('close');
			}
		}
  });
	$("#dlg_car_arrested").dialog({autoOpen: false,
		resizable: false,
		modal: true,
		buttons: {
			'Yes': function() {
				$(this).dialog('close');
				window.location.href = $('#car_arrested').attr('href');
			},
			'No': function() { 
				$(this).dialog('close');
			}
		}
  });
	$("#dlg_car_injured").dialog({autoOpen: false,
		resizable: false,
		modal: true,
		buttons: {
			'Yes': function() {
				$(this).dialog('close');
				window.location.href = $('#car_injured').attr('href');
			},
			'No': function() { 
				$(this).dialog('close');
			}
		}
  });
}*/

var btn = {
	init : function() {
	    if (!document.getElementById || !document.createElement || !document.appendChild) return false;
	    as = btn.getElementsByClassName('btn(.*)');
	    for (i=0; i<as.length; i++) {
	        if ( as[i].tagName == "INPUT" && ( as[i].type.toLowerCase() == "submit" || as[i].type.toLowerCase() == "button" ) ) {
	            var a1 = document.createElement("a");
	            a1.appendChild(document.createTextNode(as[i].value));
	            a1.className = as[i].className;
	            a1.id = as[i].id;
							if (as[i].type.toLowerCase() == 'submit'){
								btn.addEvent(a1,'click',function() {
										var form = btn.findForm(this);
	        					form.submit();
								});
							}							
	            as[i] = as[i].parentNode.replaceChild(a1, as[i]);
	            as[i] = a1;
	            as[i].style.cursor = "pointer";
	        }
	        else if (as[i].tagName == "A" || as[i].tagName == "SPAN" || as[i].tagName == "DIV"){
							var tt = as[i].childNodes;
					}
	        else {return false};
	        var i1 = document.createElement('i');
	        var i2 = document.createElement('i');
	        var s1 = document.createElement('span');
	        var s2 = document.createElement('span');
	        s1.appendChild(i1);
	        s1.appendChild(s2);
	        while (as[i].firstChild) {
	          s1.appendChild(as[i].firstChild);
	        }
	        as[i].appendChild(s1);
	        as[i] = as[i].insertBefore(i2, s1);
	    }
	    // The following lines submits the form if the button id is "submit_btn"
	    btn.addEvent(document.getElementById('submit_btn'),'click',function() {
	        var form = btn.findForm(this);
	        form.submit();
	    });
	    // The following lines resets the form if the button id is "reset_btn"
	    btn.addEvent(document.getElementById('reset_btn'),'click',function() {
	        var form = btn.findForm(this);
	        form.reset();
	    });
	},
	findForm : function(f) {
	    while(f.tagName != "FORM") {
	        f = f.parentNode;
	    }
	    return f;
	},
	addEvent : function(obj, type, fn) {
	    if (obj){
	        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]);
	        }
	    }
	},
	getElementsByClassName : function(className, tag, elm) {
	    var testClass = new RegExp("(^|\s)" + className + "(\s|$)");
	    var tag = tag || "*";
	    var elm = elm || document;
	    var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
	        var returnElements = [];
	        var current;
	        var length = elements.length;
	        for(var i=0; i<length; i++){
	            current = elements[i];
	            if(testClass.test(current.className)){
	                returnElements.push(current);
	            }
	        }
	        return returnElements;
	    }
	}
	
btn.addEvent(window,'load', function() {btn.init();} );


