//Global Settings

var borderError = "1px solid #ffd3b4";
var bgcolorError = "#ffeae0";


function validateWRTP(typeAction){
	var hotelDescription = document.getElementById("hotel_description");
	var warningBox = document.getElementById("warning-box");

	var errorOcurred = "";
	if (hotelDescription.value==""){
		hotelDescription.style.border = borderError;
		hotelDescription.style.background = bgcolorError;
		errorOcurred = '<img src="/extranet/img/icons/icon_error.gif" border="0"/> Please enter a Description<br>';
	}

	if (errorOcurred != ""){
		window.location = "#warning-anchor";
		warningBox.style.display = "block";
		warningBox.innerHTML = errorOcurred;
		return false;
	}

}

function enableDisable(theObject, orgText){

	if (theObject.readOnly == false){
		if (theObject.value==orgText){
			theObject.readOnly == true;
		}
	} else {
		//It is readonly and now we want to make it editable
		theObject.readOnly = false;
	}
}

function ajaxCall(arrayParams, idContainer, nameFuction, timeOut, layoutType, quoteParams){
	/*
		Generic Function that will call the actual Function that will interact with the Database preferably via ajax
		Main functionality of this function is to be able to see the cool waiting image
		Parameters:
			arrayParams  - Here we receive the parameters that are needed for the actual database interaction
						   	  * If a single Parameter is needed a single value will be received
							  * If MULTIPLE parameters are needed then an array is received. such as array(id, 'value')
			idContainer  - Id of the container, usually a div or a table
			nameFunction - Name of the function that will actually interact with the Database
	*/


	timeOut = (typeof timeOut == 'undefined') ? 900 : timeOut;
	layoutType = (typeof layoutType == 'undefined') ? 0 : layoutType;
	quoteParams = (typeof quoteParams == 'undefined') ? 1 : quoteParams;

	//alert("quoteParams:"+quoteParams+"to:"+timeOut+":layoutType:"+layoutType);

	var uniqueId;

	uniqueId = document.getElementById(idContainer);

	if (quoteParams!= 0){
		switch (layoutType){
			case 0: //IE is not able to obtain the form elements and their values if innerHTML is set
					uniqueId.innerHTML = '<center><img src="/images-generic/ajax-loader19.gif" border="0" /></center>';
					break;
			case 1: uniqueId.innerHTML = '<td colspan="3" align="center"><img src="/images-generic/ajax-loader19.gif" border="1" height="32" width="32"/></td>';
					break;
			case 2: //IE is not able to obtain the form elements and their values if innerHTML is set
					uniqueId.innerHTML = '<center><img src="images/switcher-loader.gif" border="0" class="loader" /></center>';
					break;
		}
	}

	switch (quoteParams){
		case 0: updateRole(arrayParams, idContainer);
				break;
		case 1: window.setTimeout(nameFuction+'("'+arrayParams+'", "'+idContainer+'", 1)', timeOut);
				break;
	}


}

function wrtpPermissionsPageBreak(idRow, idContainer){
	var uniqueId, filterWebsite, sortByWebsite, pageBreak, theUser, theLogin;

	uniqueId = document.getElementById(idContainer);
	filterWebsite = document.getElementById("egWebsite").value;
	sortByWebsite = document.getElementById("store_sort_by").value;

	theUser = document.getElementById("pk_user").value;
	theLogin = document.getElementById("user_login").value;

	//do all DB Stuff:
	ajax=startAjax();

	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) { //todo OK
			if (ajax.responseText=="false"){

			} else {
				uniqueId.innerHTML = "";
				uniqueId.innerHTML = ajax.responseText;
			}
		}
	}

	ajax.open("GET", "/extranet/ajaxFunctions.php?func=wrtp&task=page_break_permissions&page="+idRow+"&website="+filterWebsite+"&user="+theUser+"&login="+theLogin);

	ajax.send(null);
}

function wrtpPageBreak(idRow, idContainer){
	var uniqueId, filterWebsite, sortByWebsite, pageBreak, current_user;

	uniqueId = 		document.getElementById(idContainer);
	filterWebsite = document.getElementById("egWebsite").value;
	sortByWebsite = document.getElementById("store_sort_by").value;
	current_user =  document.getElementById("current_user").value;
	//do all DB Stuff:
	ajax=startAjax();

	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) { //todo OK
			if (ajax.responseText=="false"){

			} else {
				uniqueId.innerHTML = "";
				uniqueId.innerHTML = ajax.responseText;
			}
		}
	}

	ajax.open("GET", "/extranet/ajaxFunctions.php?func=wrtp&task=page_break&page="+idRow+"&website="+filterWebsite+"&sort_by="+sortByWebsite+"&current_user="+current_user);

	ajax.send(null);
}

function wrtpOrderVersions(idRow, idContainer){
	var uniqueId, varEditing, filterWebiste, storeSortBy, current_user;

	uniqueId = document.getElementById(idContainer);
	filterWebiste = document.getElementById("egWebsite").value;
	storeSortBy = document.getElementById("store_sort_by");
	current_user = document.getElementById("current_user").value;
	storeSortBy.value = idRow;
	idRow = idRow.split("@");
	varEditing = "";

	if (idRow[2]=="1"){
		varEditing = "editing";
	}

	//do all DB Stuff:
	ajax=startAjax();

	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) { //todo OK
			if (ajax.responseText=="false"){

			} else {
				uniqueId.innerHTML = "";
				uniqueId.innerHTML = ajax.responseText;
				//changePageBreak("count_order_versions", idRow[0], idRow[1], varEditing, filterWebiste);
			}
		}
	}

	ajax.open("GET", "/extranet/ajaxFunctions.php?func=wrtp&task=order_versions&language="+idRow[0]+"&version="+idRow[1]+"&status="+varEditing+"&website="+filterWebiste+"&current_user="+current_user);

	ajax.send(null);
}

function wrtpOtherVersions(idRow, idContainer){
	var uniqueId, previousConfirmationMail, previousOnArrivalMail;

	uniqueId = document.getElementById(idContainer);
	previousConfirmationMail = document.getElementById("previousConfirmationMail");
	previousOnArrivalMail = document.getElementById("previousOnArrivalMail");

	idRow = idRow.split("@");
	//do all DB Stuff:
	ajax=startAjax();

	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) { //todo OK
			if (ajax.responseText=="false"){

			} else {
				uniqueId.innerHTML = "";
				strResponse = ajax.responseText.split("<!-- FIN -->");
				uniqueId.innerHTML = "<div style='width:390px;display:block;'>"+strResponse[0]+"</div>";
				previousConfirmationMail.innerHTML = strResponse[1];
				previousOnArrivalMail.innerHTML = strResponse[2];
			}
		}
	}

	ajax.open("GET", "/extranet/ajaxFunctions.php?func=wrtp&task=other_versions&pk_hotel="+idRow[0]+"&version="+idRow[1]+"&language="+idRow[2]);

	ajax.send(null);
}

function changePageBreak(countFunction, parOne, parTwo, parThree, parFour){
	var pageBreak;
	pageBreak =  document.getElementById("page_break");
	parTwo = (typeof parTwo == 'undefined') ? "" : parTwo;
	parThree = (typeof parThree == 'undefined') ? "" : parThree;
	parFour = (typeof parFour == 'undefined') ? "" : parFour;
	//do all DB Stuff:
	ajax=startAjax();

	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) { //todo OK
			if (ajax.responseText=="false"){

			} else {
				pageBreak.innerHTML = "";
				pageBreak.innerHTML = ajax.responseText;
			}
		}
	}

	switch (countFunction){
		case "count_filter_website": 			 ajax.open("GET", "/extranet/ajaxFunctions.php?func=wrtp&task="+countFunction+"&pk="+parOne);
									 			 break;
		case "count_filter_website_permissions": ajax.open("GET", "/extranet/ajaxFunctions.php?func=wrtp&task="+countFunction+"&pk="+parOne);
									 			 break;


		//case "count_order_versions":	ajax.open("GET", "/extranet/ajaxFunctions.php?func=wrtp&task="+countFunction+"&language="+parOne+"&version="+parTwo+"&status="+parThree+"&website="+parFour);
										break;
	}

	ajax.send(null);

}

function wrtpPermissionsPerWebsite(idRow, idContainer){
	var uniqueId, theUser, theLogin;

	uniqueId = document.getElementById(idContainer);
	idRow = document.getElementById(idRow).value;

	theUser = document.getElementById("pk_user").value;
	theLogin = document.getElementById("user_login").value;

	//do all DB Stuff:
	ajax=startAjax();

	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) { //todo OK
			if (ajax.responseText=="false"){

			} else {
				uniqueId.innerHTML = "";
				uniqueId.innerHTML = ajax.responseText;
				changePageBreak("count_filter_website_permissions", idRow);
			}
		}
	}

	ajax.open("GET", "/extranet/ajaxFunctions.php?func=wrtp&task=filter_website_permission&pk="+idRow+"&user="+theUser+"&login="+theLogin);

	ajax.send(null);
}

function wrtpPerWebsite(idRow, idContainer){
	var uniqueId, current_user;

	uniqueId = document.getElementById(idContainer);
	idRow = document.getElementById(idRow).value;
	current_user = document.getElementById("current_user").value;

	//do all DB Stuff:
	ajax=startAjax();

	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) { //todo OK
			if (ajax.responseText=="false"){

			} else {
				uniqueId.innerHTML = "";
				uniqueId.innerHTML = ajax.responseText;
				changePageBreak("count_filter_website", idRow);
			}
		}
	}

	ajax.open("GET", "/extranet/ajaxFunctions.php?func=wrtp&task=filter_website&pk="+idRow+"&current_user="+current_user);

	ajax.send(null);
}

function modifyRole(idRow, idContainer){
	var uniqueId;

	uniqueId = document.getElementById(idContainer);

	//do all DB Stuff:
	ajax=startAjax();

	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) { //todo OK
			if (ajax.responseText=="false"){

			} else {
				uniqueId.innerHTML = "";
				uniqueId.innerHTML = ajax.responseText;
			}
		}
	}

	ajax.open("GET", "/extranet/ajaxFunctions.php?func=roles&task=edit&pk="+idRow);

	ajax.send(null);


}



function updateRole(xForm, idContainer){

	var uniqueId = document.getElementById(idContainer);

	var pk_role = xForm.pk_role.value;
	var role_desc = xForm.role_description.value;
	//do all DB Stuff:
	ajax=startAjax();
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) { //todo OK
			if (ajax.responseText=="false"){

			} else {
				uniqueId.innerHTML = ajax.responseText;
			}
		}
	}

	ajax.open("GET", "/extranet/ajaxFunctions.php?func=roles&task=update&pk="+pk_role+"&desc="+role_desc);
	ajax.send(null);

}

function updateRoleStatus(arrayParams, idContainer){
	var uniqueId = document.getElementById(idContainer);
	arrayParams = arrayParams.split("@");
	var pk_role = arrayParams[0];
	var status_role = arrayParams[1];
	//do all DB Stuff:
	ajax=startAjax();
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) { //todo OK
			if (ajax.responseText=="false"){

			} else {
				uniqueId.innerHTML = ajax.responseText;
			}
		}
	}

	ajax.open("GET", "/extranet/ajaxFunctions.php?func=roles&task=status&pk="+pk_role+"&status="+status_role);
	ajax.send(null);

}

function deleteRole(idRow, idContainer){
	var uniqueId = document.getElementById(idContainer);

	//do all DB Stuff:
	ajax=startAjax();
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) { //todo OK
			if (ajax.responseText=="false"){

			} else {
				uniqueId.innerHTML = ajax.responseText;
			}
		}
	}

	ajax.open("GET", "/extranet/ajaxFunctions.php?func=roles&task=delete&pk="+idRow);
	ajax.send(null);

}

function deleteUser(idRow, idContainer){
	var uniqueId = document.getElementById(idContainer);

	//do all DB Stuff:
	ajax=startAjax();
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) { //todo OK
			if (ajax.responseText=="false"){

			} else {
				uniqueId.innerHTML = ajax.responseText;
			}
		}
	}

	ajax.open("GET", "/extranet/ajaxFunctions.php?func=users&task=delete-user&pk="+idRow);
	ajax.send(null);

}

function submitRoles(roleName, roleDescription){
	var roleName = document.getElementById(roleName);
	var roleDescription = document.getElementById(roleDescription);
	var warningBox = document.getElementById("warning-box");
	var errorOcurred = "";
	if (roleName.value==""){
		roleName.style.border = borderError;
		roleName.style.background = bgcolorError;
		errorOcurred = '<img src="/extranet/img/icons/icon_error.gif" border="0"/> Please enter a Role Name<br>';
	}
	if (roleDescription.value==""){
		roleDescription.style.border = borderError;
		roleDescription.style.background = bgcolorError;
		errorOcurred+= '<img src="/extranet/img/icons/icon_error.gif" border="0"/> Please enter a Role Description<br>';
	}

	if (errorOcurred != ""){
		warningBox.style.display = "block";
		warningBox.innerHTML = errorOcurred;
		return false;
	}

	//do all DB Stuff:
	ajax=startAjax();
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) { //todo OK
			if (ajax.responseText=="true"){
				//This Role Name already exist - Role Name must be unique
				warningBox.style.display = "block";
				roleName.style.border = borderError;
				roleName.style.background = bgcolorError;
				warningBox.innerHTML = '<img src="/extranet/img/icons/icon_error.gif" border="0"/> Sorry, that Role Name already exists. Please choose another.';
			} else {
				document.location = "roles.php";
			}
		}
	}

	ajax.open("GET", "/extranet/ajaxFunctions.php?func=roles&task=validate&pk="+roleName.value+"&desc="+roleDescription.value);
	ajax.send(null);

}


// Create Users
function submitUsers(userName, userLogin, userPhone, userPassword, userConfirmPassword){
	var userName = document.getElementById(userName);
	var userLogin = document.getElementById(userLogin);
	var userPhone = document.getElementById(userPhone);
	var userPassword = document.getElementById(userPassword);
	var userConfirmPassword = document.getElementById(userConfirmPassword);
	var warningBox = document.getElementById("warning-box");
	var errorOcurred = "";
	var checkEmailAddress = checkValidation ( userLogin );

	if (userName.value==""){
		userName.style.border = borderError;
		userName.style.background = bgcolorError;
		errorOcurred = '<img src="/extranet/img/icons/icon_error.gif" border="0"/> Please enter a Name for this User<br>';
	}
	if (checkEmailAddress!=""){
		errorOcurred+= '<img src="/extranet/img/icons/icon_error.gif" border="0"/> '+checkEmailAddress+'<br>';
	}
	if (userPassword.value==""){
		userPassword.style.border = borderError;
		userPassword.style.background = bgcolorError;
		errorOcurred+= '<img src="/extranet/img/icons/icon_error.gif" border="0"/> Please enter a Password for this User<br>';
	}
	if (userPassword.value!=userConfirmPassword.value){
		userPassword.style.border = borderError;
		userPassword.style.background = bgcolorError;
		errorOcurred+= '<img src="/extranet/img/icons/icon_error.gif" border="0"/> Sorry, Passwords do not match<br>';
	}

	if (errorOcurred != ""){
		warningBox.style.display = "block";
		warningBox.innerHTML = errorOcurred;
		return false;
	}

	//do all DB Stuff:
	ajax=startAjax();
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) { //todo OK
		warningBox.style.display = "block";
		warningBox.innerHTML = ajax.responseText;
			if (ajax.responseText=="true"){
				//This User Login already exist - User Login must be unique
				warningBox.style.display = "block";
				userName.style.border = borderError;
				userName.style.background = bgcolorError;
				warningBox.innerHTML = '<img src="/extranet/img/icons/icon_error.gif" border="0"/> Sorry, that Email Address(Login) already exists. Please choose another.';
			} else {
				document.location = "wrtp-roles.php";
			}
		}
	}

	ajax.open("GET", "/extranet/ajaxFunctions.php?func=users&task=validate-user&login="+userLogin.value+"&name="+userName.value+"&phone="+userPhone.value+"&pass="+userPassword.value);
	ajax.send(null);
}

// Edit User
function editUsers(userName, userLogin, userPhone, userPassword, userConfirmPassword){
	var userName = document.getElementById(userName);
	var userLogin = document.getElementById(userLogin);
	var userPhone = document.getElementById(userPhone);
	var userPassword = document.getElementById(userPassword);
	var userConfirmPassword = document.getElementById(userConfirmPassword);
	var warningBox = document.getElementById("warning-box");
	var errorOcurred = "";
	var checkEmailAddress = checkValidation ( userLogin );

	if (userName.value==""){
		userName.style.border = borderError;
		userName.style.background = bgcolorError;
		errorOcurred = '<img src="/extranet/img/icons/icon_error.gif" border="0"/> Please enter a Name for this User<br>';
	}
	if (checkEmailAddress!=""){
		errorOcurred+= '<img src="/extranet/img/icons/icon_error.gif" border="0"/> '+checkEmailAddress+'<br>';
	}
	if (userPassword.value==""){
		userPassword.style.border = borderError;
		userPassword.style.background = bgcolorError;
		errorOcurred+= '<img src="/extranet/img/icons/icon_error.gif" border="0"/> Please enter a Password for this User<br>';
	}
	if (userPassword.value!=userConfirmPassword.value){
		userPassword.style.border = borderError;
		userPassword.style.background = bgcolorError;
		errorOcurred+= '<img src="/extranet/img/icons/icon_error.gif" border="0"/> Sorry, Passwords do not match<br>';
	}

	if (errorOcurred != ""){
		warningBox.style.display = "block";
		warningBox.innerHTML = errorOcurred;
		return false;
	}
	return true;
}



function selectCheckBoxes(currentCheckBox, allCheckBoxes){
	var checkStatus;
	currentCheckBox = document.getElementById(currentCheckBox);
	newCheckBox = currentCheckBox.value == 0? 1 : 0;
	currentCheckBox.value = newCheckBox;
	checkStatus = newCheckBox == 1? true : false;

	for (i = 0; i < allCheckBoxes.length; i++){
		allCheckBoxes[i].checked = checkStatus;
	}
}

function selectUserPermsissionsCheckBoxes(currentCheckBox, jsLanguage, jsPermissions ){
	var checkStatus;
	checkStatus = document.getElementById("cb_"+jsLanguage+"_"+jsPermissions);
	newCheckBox = checkStatus.value == 0? 1 : 0;
	checkStatus.value = newCheckBox; //updating hidden fields
	//Changing BG Image
	newImage = checkStatus.value == 0? "url(img/icons/bg-all-permissions-no.gif)" : "url(img/icons/bg-all-permissions-yes.gif)";
	bgImage = document.getElementById("a_"+jsLanguage+"_"+jsPermissions);

	bgImage.style.backgroundImage = newImage;
	newCheckBox = newCheckBox == 0? false : true;
	var x = document.wrtpform.getElementsByTagName('input');
	//We're going to have to loop all checkboxes
	for (var i=0;i<x.length;i++){
		//We now need to get ONLY checkboxes for given Languange and Permission Level
		// eg. We want to check/uncheck all permissions for English Translations
		if ((x[i].type == "checkbox") && (x[i].className == jsLanguage+'_'+jsPermissions)){
			x[i].checked = newCheckBox;
		}
	}
}

function wrtpLoading(){
	var theContainer;
	theContainer = document.getElementById("wrtpContainer");
	theContainer.innerHTML = '<center><img src="/images-generic/ajax-loader19.gif" border="0" /></center>';
	window.setTimeout('wrtpPageBreak("1", "wrtpContainer")', 1000);
	//window.onload = alert("hola");
}

// Ajax Initialization Function
function startAjax(){
	var xmlhttp=false;
 	try {
 		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
 	} catch (e) {
 		try {
 			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
 		} catch (E) {
 			xmlhttp = false;
 		}
  	}

	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
 		xmlhttp = new XMLHttpRequest();
	}
	return xmlhttp;
}

function countWords(idTextArea, idCountMessage){
	document.getElementById(idCountMessage).innerHTML = document.getElementById(idTextArea).value.split(' ').length;
}

//Generic Email Validations
function checkValidation ( addressField ) {
	var strError;
	strError = "";
    if ( stringEmpty ( addressField.value ) )
        strError = "Error! There is no E-Mail address entered" ;
    else if ( noAtSign ( addressField.value ) )
        strError =  "Error! The E-Mail address does not contain an '@' character";
    else if ( nothingBeforeAt ( addressField.value ) )
        strError =  "Error! An E-Mail address must contain at least one character before the '@' character";
    else if ( noLeftBracket ( addressField.value ) )
        strError =  "Error! The E-Mail address contains a right square bracket ']',\nbut no corresponding left square bracket '['";
    else if ( noRightBracket ( addressField.value ) )
        strError =  "Error! The E-Mail address contains a left square bracket '[',\nbut no corresponding right square bracket ']'";
    else if ( noValidPeriod ( addressField.value ) )
        strError =  "Error! An E-Mail address must contain a period ('.') character";
    else if ( noValidSuffix ( addressField.value ) )
        strError =  "Error! An E-Mail address must contain a two or three character suffix";

    return ( strError );
}

function linkCheckValidation ( formField ) {
    if ( checkValidation ( formField ) == true ) {
        alert ( 'E-Mail Address Validates OK' );
    }

    return ( false );
}

function stringEmpty ( address ) {
    // CHECK THAT THE STRING IS NOT EMPTY
    if ( address.length < 1 ) {
        return ( true );
    } else {
        return ( false );
    }
}

function noAtSign ( address ) {
    // CHECK THAT THERE IS AN '@' CHARACTER IN THE STRING
    if ( address.indexOf ( '@', 0 ) == -1 ) {
        return ( true )
    } else {
        return ( false );
    }
}

function nothingBeforeAt ( address ) {
    // CHECK THERE IS AT LEAST ONE CHARACTER BEFORE THE '@' CHARACTER
    if ( address.indexOf ( '@', 0 ) < 1 ) {
        return ( true )
    } else {
        return ( false );
    }
}

function noLeftBracket ( address ) {
    // IF EMAIL ADDRESS IN FORM 'user@[255,255,255,0]', THEN CHECK FOR LEFT BRACKET
    if ( address.indexOf ( '[', 0 ) == -1 && address.charAt ( address.length - 1 ) == ']' ) {
        return ( true )
    } else {
        return ( false );
    }
}

function noRightBracket ( address ) {
    // IF EMAIL ADDRESS IN FORM 'user@[255,255,255,0]', THEN CHECK FOR RIGHT BRACKET
    if ( address.indexOf ( '[', 0 ) > -1 && address.charAt ( address.length - 1 ) != ']' ) {
        return ( true );
    } else {
        return ( false );
    }
}

function noValidPeriod ( address ) {
    // IF EMAIL ADDRESS IN FORM 'user@[255,255,255,0]', THEN WE ARE NOT INTERESTED
    if ( address.indexOf ( '@', 0 ) > 1 && address.charAt ( address.length - 1 ) == ']' )
        return ( false );

    // CHECK THAT THERE IS AT LEAST ONE PERIOD IN THE STRING
    if ( address.indexOf ( '.', 0 ) == -1 )
        return ( true );

    return ( false );
}

function noValidSuffix ( address ) {
    // IF EMAIL ADDRESS IN FORM 'user@[255,255,255,0]', THEN WE ARE NOT INTERESTED
    if ( address.indexOf ( '@', 0 ) > 1 && address.charAt ( address.length - 1 ) == ']' )
        return ( false );

    // CHECK THAT THERE IS A TWO OR THREE CHARACTER SUFFIX AFTER THE LAST PERIOD
    var len = address.length;
    var pos = address.lastIndexOf ( '.', len - 1 ) + 1;
    if ( ( len - pos ) < 2 || ( len - pos ) > 3 ) {
        return ( true );
    } else {
        return ( false );
    }
}


// GMAPS

function setupMap(jsLat, jsLon, jsZoom) {
     if (GBrowserIsCompatible()) {
       map = new GMap2(document.getElementById("map"));
    map.addControl(new GLargeMapControl(),new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(5,5)));
    map.addControl(new GMapTypeControl(),new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(5,18)));
    map.addControl(new GOverviewMapControl(),new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(2,20)));

	map.setCenter(new GLatLng(jsLat, jsLon), 8 );
       map.setZoom(jsZoom);
       map.setMapType(G_NORMAL_MAP);

       map.enableDoubleClickZoom();
	//Load Bar, Restaurants...
	setupGuideEstablishments();
	//Load all HOTELS
       //window.setTimeout(setupWatchers, 0);
     }
   }


   function getIcons(typeIcon) {
     var i = 0;
     if (!ICONS[i]) {
       var icon = new GIcon();

	switch(typeIcon){
        case "bars":  icon.image = "/images-generic/icon-guide-bar.gif";
					  icon.iconSize = new GSize(20, 34);
					  break;
        case "clubs": icon.image = "/images-generic/icon-guide-club.gif";
					  icon.iconSize = new GSize(20, 34);
					  break;
        case "restaurants": icon.image = "/images-generic/icon-guide-resto.gif";
		              icon.iconSize = new GSize(20, 34);
					  break;
	}
       icon.iconAnchor = new GPoint(16, 16);
       icon.infoWindowAnchor = new GPoint(16, 0);

       //icon.shadow = "images/" + IMAGES[i] + "-shadow.png";
       //icon.shadowSize = new GSize(59, 32);
       ICONS[i] = icon;
     }
     return ICONS[i];
   }

   function createMarker(pointLat, pointLng, contentHTML, contentWidth, typeIcon) {
     var point = new GLatLng(pointLat, pointLng);

	typeIcon = (typeof typeIcon == 'undefined') ? "" : typeIcon;

	 if (typeIcon != ""){
	 	marker = new GMarker(point, getIcons(typeIcon));
	 } else {
	 	marker = new GMarker(point);
	 }

     GEvent.addListener(marker, "click", function() {
       map.openInfoWindowHtml(point, '<div style="width: '+contentWidth+'">'+contentHTML+'</div>');
       });

     return marker;
   }

function submitGroups(isplaces){
	var uniqueId = document.getElementById('container');
	var warningBox = document.getElementById("warning-box");
	var successMessage = document.getElementById("successMessage");
	var emailAddress = document.getElementById('emailAddress');
	var originalHTML = document.getElementById('originalHTML');
	var errorOcurred = "";
	var nameFunction = "";
	var checkEmailAddress = checkValidation ( emailAddress );

	//Form Elements
	var numberPeople = document.getElementById('numberPeople');
	var ARRIVAL = document.getElementById('GROUPARRIVAL');
	var DEPARTURE = document.getElementById('GROUPDEPARTURE');
	if (isplaces) {
		var GDestination = document.getElementById('gDestination');
	}
	var Single = document.getElementById('Single').value;
	var Twin = document.getElementById('Twin').value;
	var Double = document.getElementById('Double').value;
	var Triple = document.getElementById('Triple').value;
	var Quads = document.getElementById('Quads').value;
	var Comments = document.getElementById('comments').value;
	var firstName = document.getElementById('firstName').value;
	var surName = document.getElementById('surName').value;
	var phone = document.getElementById('phone').value;
	var groupEmail = document.getElementById('groupEmail').value;

	//User Messages
	var emptyEmail = document.getElementById('emptyEmail').value;
	var errorEmail = document.getElementById('errorEmail').value;
	var emptyNumberPeople = document.getElementById('emptyNumberPeople').value;
	var emptyARRIVAL = document.getElementById('emptyARRIVAL').value;
	var emptyDEPARTURE = document.getElementById('emptyDEPARTURE').value;
	var emptyDATE = document.getElementById('defaultDate').value;
	if (isplaces) {
		var emptyDest = document.getElementById('emptyDest').value;
	}

	//Clear error box
	warningBox.innerHTML = "5";
	warningBox.style.display = "none";
	successMessage.innerHTML = "";
	successMessage.style.display = "none";
	window.location = "#backTo";
	//Destination
	if (isplaces) {
		if (GDestination.value==""){
			GDestination.style.border = borderError;
			GDestination.style.background = bgcolorError;
			errorOcurred+= '<img src="/extranet/img/icons/icon_error.gif" border="0"/> '+emptyDest+'<br>';
		}
	}
	//Number of people in group
	if (numberPeople.value==""){
		numberPeople.style.border = borderError;
		numberPeople.style.background = bgcolorError;
		errorOcurred+= '<img src="/extranet/img/icons/icon_error.gif" border="0"/> '+emptyNumberPeople+'<br>';
	}
	//Arrival Date
	if (ARRIVAL.value=="" || ARRIVAL.value == emptyDATE){
		ARRIVAL.style.border = borderError;
		ARRIVAL.style.background = bgcolorError;
		errorOcurred+= '<img src="/extranet/img/icons/icon_error.gif" border="0"/> '+emptyARRIVAL+'<br>';
	}
	//Departure Date
	if (DEPARTURE.value=="" || DEPARTURE.value == emptyDATE){
		DEPARTURE.style.border = borderError;
		DEPARTURE.style.background = bgcolorError;
		errorOcurred+= '<img src="/extranet/img/icons/icon_error.gif" border="0"/> '+emptyDEPARTURE+'<br>';
	}

	if (emailAddress.value==""){
		emailAddress.style.border = borderError;
		emailAddress.style.background = bgcolorError;
		errorOcurred+= '<img src="/extranet/img/icons/icon_error.gif" border="0"/> '+emptyEmail;
	} else {
		if (checkEmailAddress!=""){
			emailAddress.style.border = borderError;
			emailAddress.style.background = bgcolorError;
			errorOcurred+= '<img src="/extranet/img/icons/icon_error.gif" border="0"/> '+errorEmail;
		}
	}

	if (errorOcurred != ""){
		warningBox.style.display = "block";
		warningBox.innerHTML = errorOcurred;
		return false;
	}
	//Get values before putting rolling ball
	if (isplaces) {
		var theDestination = GDestination.value;
	} else {
		var theDestination = '';
	}
	var numberPeople = document.getElementById('numberPeople').value;
	var ARRIVAL = document.getElementById('GROUPARRIVAL').value;
	var DEPARTURE = document.getElementById('GROUPDEPARTURE').value;

	emailAddress = emailAddress.value;
	originalHTML.value = uniqueId.innerHTML;

	uniqueId.innerHTML = '<center style="margin-top:10px;"><img src="/add-ons/img/common/ajax-loader19.gif" border="0" /></center>';
	nameFunction = 'sendGroupEmail("'+theDestination+'", "'+numberPeople+'", "'+ARRIVAL+'", "'+DEPARTURE+'", "'+Single+'", "'+Twin+'", "'+Double+'", "'+Triple+'", "'+Quads+'", "'+Comments+'", "'+firstName+'", "'+surName+'", "'+emailAddress+'", "'+phone+'", "'+groupEmail+'")';
	window.setTimeout(nameFunction, 900);
	//alert(nameFunction);

	return false;
}

function sendGroupEmail(theDestination, numberPeople, ARRIVAL, DEPARTURE, Single, Twin, Double, Triple, Quads, Comments, firstName, surName, emailAddress, phone, groupEmail){
	var uniqueId = document.getElementById('container');
	var originalHTML = document.getElementById('originalHTML');
	var successMessage = document.getElementById("successMessage");
	var success = document.getElementById('success').value;
	//do all DB Stuff:
	ajax=startAjax();
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) { //todo OK
			successMessage.style.display = "block";
			successMessage.innerHTML = success;
			uniqueId.innerHTML = originalHTML.value;
		}
	}

	ajax.open("GET", "/ajax/ajaxFunctions.php?func=groupings&task=send&desti="+theDestination+"&number="+numberPeople+"&ARRIVAL="+ARRIVAL+"&DEPARTURE="+DEPARTURE+"&Single="+Single+"&Twin="+Twin+"&Double="+Double+"&Triple="+Triple+"&Quads="+Quads+"&comments="+Comments+"&firstName="+firstName+"&surName="+surName+"&email="+emailAddress+"&phone="+phone+"&groupEmail="+groupEmail);
	ajax.send(null);
	return false;
}

function changeLocation(newLocation, additionalParams){
	document.location = newLocation + "?month=" + additionalParams.value;
}


   // Helper function to verify if value,text is present in selected list.
   // This function is used by one2two() for verifying if the value being
   // moved is already present in the destination.
   function checkForPresenceInSelect2(optVal, text, selList) {
     for (i = 0; i < selList.length; i++) {
       if (selList.options[i].value == optVal) return true;
       if (selList.options[i].text == text) return true;
     }
     return false;
   }

   // Logic for moving a multi-select from element1 to element2
   function one2two(element1, element2) {

     var memberList = document.getElementById(element1); //All the POI's
     var selectedList = document.getElementById(element2); //The Selected POI's
     var len = memberList.length;
     for (var i = 0; i < len; ++i) {
       if (memberList.options[i].selected == true) {
         memberList.options[i].selected = false;
         if (selectedList.length < 4 && checkForPresenceInSelect2(memberList.options[i].value, memberList.options[i].text, selectedList) == false) {
           selectedList.options[selectedList.length] = new Option(memberList.options[i].text, memberList.options[i].value);
         }
       }
     }
   }

   function one2twoHotels(element1, element2) {
     var memberList = document.getElementById(element1); //All the POI's
     var selectedList = document.getElementById(element2); //The Selected POI's
     var len = memberList.length;
     for (var i = 0; i < len; ++i) {
       if (memberList.options[i].selected == true) {
         memberList.options[i].selected = false;
         if (selectedList.length < 3 && checkForPresenceInSelect2(memberList.options[i].value, memberList.options[i].text, selectedList) == false) {
           selectedList.options[selectedList.length] = new Option(memberList.options[i].text, memberList.options[i].value);
         }
       }
     }
   }
   
   function one2twoEventsHotels(element1, element2) {
     var memberList = document.getElementById(element1); //All the Hotels
     var selectedList = document.getElementById(element2); //The Selected Hotels
     var len = memberList.length;
     for (var i = 0; i < len; ++i) {
       if (memberList.options[i].selected == true) {
         memberList.options[i].selected = false;
         if (selectedList.length < 3 && checkForPresenceInSelect2(memberList.options[i].value, memberList.options[i].text, selectedList) == false) {
           selectedList.options[selectedList.length] = new Option(memberList.options[i].text, memberList.options[i].value, memberList.options[i].selected = true);
         }
       }
     }
   }
   
   function checkEventHotelsAndNavigate(theForm){
    alert("hello");
    return false;      
   }
   
   
   

   // moving a multi-select from element2 to element1.
   // Actually this assumes that the values being moved are
   // already present in element1 and ends up deleting
   // the selected values in element2.
   function two2one(element1, element2) {
     var selectedList = document.getElementById(element2);
     for (i = selectedList.length -1; i >= 0; i--) {
       if (selectedList.options[i].selected == true) {
         selectedList.options[i] = null;
       }
     }
   }


   function checkAndNavigate() {
     var poiSelected = document.getElementById("selected_poi");
     if (poiSelected.length < 1) {
       //if (!confirm("You have neither not selected any Point of Interest or have removed them all. Would you like to continue?")){
		alert("You have not selected any Points of Interest to be featured");
		return false;
       //}
     }

     for (var k = 0; k < poiSelected.length; k++) {
       poiSelected.options[k].selected = true;
     }

     return true;
   }

   function checkHotelsAndNavigate(theForm) {
	//We only want to validate if we're NOT uploading an image
	if (theForm.task.value!="save_poi_pic"){
	     var listSelectedHotels = document.getElementById("list_selected_hotels");
	     var timesPrompted = 0;
		 listSelectedHotels = listSelectedHotels.value.split("@");
		 //We know how many POI's were selected and now lets loop these many time
	     for (x = 0; x < listSelectedHotels.length; x++){
			var theSelected = document.getElementById(listSelectedHotels[x]);
			//We need to select at least one hotel per POI
		    if (theSelected.length < 1 && timesPrompted < 1) {
				alert("One or more does not have a POI associated to it");
				//We only want to show an alert once so we return false here and count the number of times prompted just in case
				return false;
		       	timesPrompted++;
		    }
		    for (var k = 0; k < theSelected.length; k++) {
		       theSelected.options[k].selected = true;
		    }
	     }
	}
	return true;
   }

function changeFeaturedLocation(theTask, theNewLocation){
	document.location = "?task="+theTask+"&featured_web="+theNewLocation.value;
}


function changeFeaturedPOI(theTask, theFeaturedWeb){
	document.location = "?task="+theTask+"&featured_web="+theFeaturedWeb;
}

// Affiliate Screens
function deleteAffiliate(idRow, idContainer){
	var uniqueId = document.getElementById(idContainer);

	//do all DB Stuff:
	ajax=startAjax();
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) { //todo OK
			if (ajax.responseText=="false"){

			} else {
				uniqueId.innerHTML = ajax.responseText;
			}
		}
	}

	ajax.open("GET", "/extranet/ajaxFunctions.php?func=affiliates&task=delete_affiliate&pk="+idRow);
	ajax.send(null);

}


// HomePage Functions
function getHomeVideos(arrayParams, idContainer){
	var uniqueId = document.getElementById(idContainer);
	arrayParams = arrayParams.split("@");
	var video_id = arrayParams[0];
	var video_type = arrayParams[1];

	//do all DB Stuff:
	ajax=startAjax();
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) { //todo OK
			if (ajax.responseText=="false"){

			} else {
				//For some reason home page videos are not showing on IE6 unless the response code is not within single quotes
				uniqueId.innerHTML = "<!--[if lt IE 7]>'<![endif]-->"+ajax.responseText+"<!--[if lt IE 7]>'<![endif]-->";
			}
		}
	}

	ajax.open("GET", "/ajax/ajaxFunctions.php?func=videos&task=featuredVideo&video_id="+video_id+"&video_type="+video_type);
	ajax.send(null);
}

function validateCustomVideos(){
	var videoTitle = document.getElementById("video_title");
	var videoEmbed = document.getElementById("video_embed");
	var warningBox = document.getElementById("warning-box");
	var errorOcurred = "";

	if (videoTitle.value==""){
		videoTitle.style.border = borderError;
		videoTitle.style.background = bgcolorError;
		errorOcurred+= '<img src="/extranet/img/icons/icon_error.gif" border="0"/> Please indicate a Title for the Video<br>';
	}

	if (videoEmbed.value==""){
		videoEmbed.style.border = borderError;
		videoEmbed.style.background = bgcolorError;
		errorOcurred+= '<img src="/extranet/img/icons/icon_error.gif" border="0"/> Please add the Video\'s embed code<br>';
	}

	if (errorOcurred != ""){
		warningBox.style.display = "block";
		warningBox.innerHTML = errorOcurred;
		return false;
	}

	return true;

}


function validatePOIVideo(){
	var videoEmbed = document.getElementById("video_embed");
	var warningBox = document.getElementById("warning-box");
	var errorOcurred = "";

	if (videoEmbed.value==""){
		videoEmbed.style.border = borderError;
		videoEmbed.style.background = bgcolorError;
		errorOcurred+= '<img src="/extranet/img/icons/icon_error.gif" border="0"/> Please add the Video\'s embed code<br>';
	}

	if (errorOcurred != ""){
		warningBox.style.display = "block";
		warningBox.innerHTML = errorOcurred;
		return false;
	}

	return true;

}


function validateEstablishmentVideo(){
	var videoEmbed = document.getElementById("video_embed");
	var warningBox = document.getElementById("warning-box");
	var errorOcurred = "";

	if (videoEmbed.value==""){
		videoEmbed.style.border = borderError;
		videoEmbed.style.background = bgcolorError;
		errorOcurred+= '<img src="/extranet/img/icons/icon_error.gif" border="0"/> Please add the Video\'s embed code<br>';
	}

	if (errorOcurred != ""){
		warningBox.style.display = "block";
		warningBox.innerHTML = errorOcurred;
		return false;
	}

	return true;

}


function sendMailWidget(hotel){
	if(confirm("You are about to send an email to this establishment, do you want to continue?")){
		document.location = "widget_operations.php?act=send&h="+hotel;
	}
}

function removeHotelWidget(hotel){
	if(confirm("You are about to remove this establishment, do you want to continue?")) {
		document.location = "widget_operations.php?act=remove&h="+hotel;
	}
}



