var hideMaliciousObjectsTimer;
var IE = document.all?true:false


var batangaMouseX = 0;
var batangaMouseY = 0;
var mouseElement = null;

//the variable dontcapturemouse will allow to disable this costly code for capturing mouse position 
//if (typeof(dontcapturemouse) == "undefined" || !dontcapturemouse) {
    // If NS -- that is, !IE -- then set up for mouse capture
    //if (!IE) document.captureEvents(Event.MOUSEMOVE)

    // Set-up to use getMouseXY function onMouseMove
    //document.onmousemove = getMouseXY;
//}

function GetLoggedInUserID()
{
    var userId = getCookie("batangauserid");
    return userId;
}

function IsUserLoggedIn()
{    
    var batangacom = getCookie("batangacom");
    if(batangacom == null || batangacom.length == 0)
        return false;
                
    var hd = getCookie("hd");
    if(hd == null || hd.length == 0)
        return false;
    
    //not sure about this anymore!    
    var batangakey = getCookie("batangakey");
    if(batangakey == null || batangakey.length == 0)
        return false;
        
    return true;            
}

function decode(str)
{
    var textToWork = str;
    
    textToWork = textToWork.replace(/&lt;/g, "<");
    textToWork = textToWork.replace(/&gt;/g, ">");
    textToWork = textToWork.replace(/&quot;/g, "\"");
    textToWork = textToWork.replace(/&amp;/g, "&");
    textToWork = textToWork.replace(/&nbsp;/g, " ");
        
    return textToWork;
}

function copyToClipboard(id)
{
    var element = document.getElementById(id);    
    element.select();
    
    if(window.clipboardData)
    { 
        var r= clipboardData.setData('Text', element.value); 
        //alert("The code has been copied to your clipboard.");
        return 1; 
    }
    else 
    {
        return 0
    }        
}

function getMouseXY(e) 
{

	if (IE) 
	{   // grab the x-y pos.s if browser is IE	
	    e = e || window.event;
	    if(e.srcElement)
            mouseElement = e.srcElement;
        else
            mouseElement = null;
	    
	    //Anand: 9/12/07. Just use the clientX and clientY as there are JS error beging thrown when accessing the document.body!!!. This works well.
	    batangaMouseX = e.clientX;
	    batangaMouseY = e.clientY;
	    
		//batangaMouseX = e.clientX + document.body.scrollLeft;
		//batangaMouseY = e.clientY + document.body.scrollTop;
	} 
	else 
	{  
	    if(e.target)
            mouseElement = e.target;
        else
            mouseElement = null;
            
	    // grab the x-y pos.s if browser is NS
		batangaMouseX = e.pageX;
		batangaMouseY = e.pageY;
	}  
	// catch possible negative values in NS4
	if (batangaMouseX < 0){batangaMouseX = 0}
	if (batangaMouseY < 0){batangaMouseY = 0}  
  
  	return true;
}


var winW, winH;
function SetWinWidthHeightValues()
{
    if (parseInt(navigator.appVersion)>3) 
    {
 	    if (navigator.appName=="Netscape") 
 	    {
  		    winW = window.innerWidth;
  		    winH = window.innerHeight;
 	    }
 	    if (navigator.appName.indexOf("Microsoft")!=-1) 
 	    {
  		    winW = document.body.offsetWidth;
  		    winH = document.body.offsetHeight;
 	    }
    }
}


function trim(stringToTrim) 
{
    return stringToTrim.replace(/^\s+|\s+$/g,"");
}

function ltrim(stringToTrim) 
{
    return stringToTrim.replace(/^\s+/,"");
}

function rtrim(stringToTrim) 
{
    return stringToTrim.replace(/\s+$/,"");
}

function IsvalidEMailFormat(email)
{		
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	
	return filter.test(email);
}

function IsNumber(data)
{		
	var filter  = /^\d+$/;
	
	return filter.test(data);
}

function IsvalidUserNameFormat(userName)
{		
	var filter  = /^([a-zA-Z0-9])+$/;
	
	return filter.test(userName);
}

function clearUsernameStatus() 
{    
	closeTag('chkUserNameResult')
	closeTag('signupErr-UserName');
}

function closeTag(elementID)
{
	
	var element = document.getElementById(elementID);
	if(element != null)
        element.style.display = "none";
}

function showTag(elementID, text)
{
	var element = document.getElementById(elementID);
	if(element != null)
	{
	    if(text != null && text.length > 0)
	    {
	        element.innerHTML = text;
	    }
        element.style.display = "";                
    }            
}

function showErrorInfo(elementID, text)
{
	 showTag(elementID, text);
}

function GetSpamText()
{
    var language = getLanguage();
    if(language == "EN")
        return "If you can't find the confirmation email, check your trash, bulk, or spam folders. It's possible that the email went to the wrong folder.";
    else
        return "Si no puedes encontrar el mensaje de confirmaci&oacute;n, chequea la carpeta de &quot;trash&quot;, &quot;bulk&quot; o &quot;spam&quot;.  Es posible que el mensaje est&eacute; en la carpeta equivocada.";
}

function clearErrors()
{
    var allspans = document.getElementsByTagName("span"); 

    for (var i = 0; i < allspans.length; i++)
    { 
        if (allspans[i].getAttribute('id') != null && allspans[i].getAttribute('id').match('signupErr-'))
        { 
            var elementID = allspans[i].getAttribute('id');
            //alert(elementID);
            closeTag(elementID);
        }
    }
}

var objectsToHide; // = new Array(); 
function hideMaliciousObjects()
{	    
    ShowHideAllTags("object", "hidden");
    ShowHideAllTags("embed", "hidden");
    ShowHideAllTags("iframe", "hidden");
    
    clearTimeout(hideMaliciousObjectsTimer);
    hideMaliciousObjectsTimer = setTimeout("hideMaliciousObjects()", 200);
}

function ShowHideObjects(displayStyle)
{		    
    if(displayStyle == "hidden")
    {
        objectsToHide = new Array(); 
        hideMaliciousObjectsTimer = setTimeout("hideMaliciousObjects()", 200);
    }
    
    if(displayStyle == "visible")
    {	    
        clearTimeout(hideMaliciousObjectsTimer);
    }
    
    ShowHideAllTags("object", displayStyle);
    ShowHideAllTags("embed", displayStyle);
    ShowHideAllTags("iframe", displayStyle);
}

function IsHiddenByMeObject(id)
{
    try {
        for(var i = 0; i < objectsToHide.length; i++)
        {
            if(objectsToHide[i] == id)
                return true;
        }
    } catch (e) {}
    return false;
}

function ShowHideAllTags(objectType, displayStyle)
{
    var objects = document.getElementsByTagName(objectType); 

    for (var i = 0; i < objects.length; i++)
    { 
        if(displayStyle == "hidden"  && objects[i].style.visibility != "hidden" )
        {
            //alert("ShowHideAllTags:Hiding...visiblity=" + objects[i].style.visibility + ", id = " + objects[i].getAttribute('id') + ", objectsToHide.length = " + objectsToHide.length);
            if(objectType == "iframe")      //for iframe do not hide the coregistration iframe....
            { 
                var id = objects[i].getAttribute('id');
                if( id != "coregistration_silvercarrot")
                {
                    objectsToHide[objectsToHide.length] = objects[i].getAttribute('id');            
                    objects[i].style.visibility = displayStyle;                         
                }
            }
            else
            {    
                objectsToHide[objectsToHide.length] = objects[i].getAttribute('id');                            
                objects[i].style.visibility = displayStyle;                         
            }
        }
        else if(displayStyle == "visible" && IsHiddenByMeObject(objects[i].getAttribute('id')))
        {
            //alert("ShowHideAllTags:visbile...visiblity=" + objects[i].style.visibility + ", id = " + objects[i].getAttribute('id'));            
            objects[i].style.visibility = displayStyle;                
        }        
    }
}

function GetRequiredText()
{
    var language = getLanguage();
    if(language == "EN")
        return "&nbsp;required";
        
    return "&nbsp;requerido";
}

function validated()
{
    var language = getLanguage();
    
	var email = trim(document.getElementById("signupEmail").value);
    var password = trim(document.getElementById("signupPassword").value);
    var userName = trim(document.getElementById("signupUserName").value);
    var firstName = trim(document.getElementById("signupFirstName").value);
	var lastName = trim(document.getElementById("signupLastName").value);
	//var country = trim(document.getElementById("signupCountry").value);
	//var postalCode = trim(document.getElementById("signupPostalCode").value);
	var gender = trim(document.getElementById("signupGender").value);
	var month = trim(document.getElementById("signupMonth").value);
	var day = trim(document.getElementById("signupDay").value);
	var year = trim(document.getElementById("signupYear").value);
	var agree = document.getElementById("signupAgree");
	
	var errFocusField = null;
	
	//NOTE: Do the validation starting from the last field in the signup form first so that the errFocusField is setup to focus on the error field from the top-down
	if(!agree.checked)
	{
	    /*
	    var message;
	    if(language == "EN")
	        message = "You must agree to the Batanga's Terms of Service and Privacy Policy before registering.";
	    else
	        message = "Debes aceptar los T&eacute;rminos de Servicio y la Pol&iacute;tica de Privacidad de Batanga antes de registrarte.";
	    */  
	    
	    showTag("signupErr-Agree", GetRequiredText());
	    errFocusField = "signupAgree";
	}
	
	if(!document.formsignup.signupPreferredLang[0].checked && !document.formsignup.signupPreferredLang[1].checked)
    {
        showErrorInfo("signupErr-PreferredLang", GetRequiredText());
        errFocusField = "signupPreferredLang";
    }
	
    if(!document.formsignup.signupGender[0].checked && !document.formsignup.signupGender[1].checked)
    {
        showErrorInfo("signupErr-Gender", GetRequiredText());
        errFocusField = "signupGender";
    }
    
    if(month == "0" || day == "0" || year == "0")
	{
		showErrorInfo("signupErr-DOB", GetRequiredText());
		if(month == "00")
		    errFocusField = "signupMonth";
		else if(day == "0")
		    errFocusField = "signupDay";
		else
		    errFocusField = "signupYear";
	}
	else
	{    	
	    today = new Date();
	    birthDate = new Date(year, month - 1, day);    	    
	    var one_day = 1000*60*60*24;    	        	    
	    
	    var daysSinceBirth = Math.ceil((today.getTime()-birthDate.getTime())/(one_day));
	    if(daysSinceBirth < 4745)       //13 years
	    {
	        if(language == "EN")
	            showErrorInfo("signupErr-DOB", "&nbsp;must be 13+ years old");
            else
	            showErrorInfo("signupErr-DOB", "&nbsp;debes tener 13+ a&ntilde;os");
	            	    
	        errFocusField = "signupYear";
	    }
	}	
	
	if(lastName.length == 0)
	{
		showErrorInfo("signupErr-LastName", GetRequiredText());
		errFocusField = "signupLastName";
	}
	
	if(firstName.length == 0)
	{
		showErrorInfo("signupErr-FirstName", GetRequiredText());
		errFocusField = "signupFirstName";
	}
	
	if(userName.length == 0)
	{
		showErrorInfo("signupErr-UserName", GetRequiredText());
		errFocusField = "signupUserName";
	}
	else if(userName.length < 4 || userName.length > 18)
	{
		showErrorInfo("signupErr-UserName", "&nbsp;should be 4-18 charecters");    		
		errFocusField = "signupUserName";
	}
	else if(!IsvalidUserNameFormat(userName))
	{
		showErrorInfo("signupErr-UserName", "&nbsp;invalid format");    		
		errFocusField = "signupUserName";
	}

	if(password.length == 0)
	{
		showErrorInfo("signupErr-Password", GetRequiredText());
		errFocusField = "signupPassword";
	}
	else if(password.length < 5 || password.length > 12)
	{
	    if(language == "EN")
	    {
		    showErrorInfo("signupErr-Password", "&nbsp;should be 5-12 characters");
		}
		else
		{
		    showErrorInfo("signupErr-Password", "&nbsp;la contrase&ntilde;a tener entre 5-12 caracteres");
		    
		}
		errFocusField = "signupPassword";
	}
	else if(document.getElementById("signupPassword").value != document.getElementById("signupPassword2").value)
	{
	    if(language == "EN")
	    {
		    showErrorInfo("signupErr-Password", "&nbsp;passwords do not match");
		    showErrorInfo("signupErr-Password2", "&nbsp;passwords do not match");    		
		}
		else
		{
		    showErrorInfo("signupErr-Password", "&nbsp;Las contrase&ntilde;as no coinciden");
		    showErrorInfo("signupErr-Password2", "&nbsp;Las contrase&ntilde;as no coinciden");
		}
		
		errFocusField = "signupPassword";
	}    	
	
	if(email.length == 0)
	{
		showErrorInfo("signupErr-Email", GetRequiredText());
		errFocusField = "signupEmail";
	}	
	else if(!IsvalidEMailFormat(email))
	{
		showErrorInfo("signupErr-Email", "&nbsp;invalid format");    		
		showErrorInfo("signupErr-Email2", "&nbsp;invalid format");    		
		errFocusField = "signupEmail";
	}    	
	
    if(errFocusField != null)
    {
        if(document.getElementById(errFocusField) != null)
        {                
            document.getElementById(errFocusField).focus();
        }
    }
    
	return (errFocusField == null);
	
}

function validateforupdate()
{
    var language = getLanguage();
    
    var firstName = trim(document.getElementById("updateFirstName").value);
	var lastName = trim(document.getElementById("updateLastName").value);
	var gender = trim(document.getElementById("updateGender").value);
	var month = trim(document.getElementById("updateMonth").value);
	var day = trim(document.getElementById("updateDay").value);
	var year = trim(document.getElementById("updateYear").value);
	var agree = document.getElementById("updateAgree");
	
	var errFocusField = null;
	
	//NOTE: Do the validation starting from the last field in the signup form first so that the errFocusField is setup to focus on the error field from the top-down
	if(!agree.checked)
	{
	    showTag("updateErr-Agree", GetRequiredText());
	    errFocusField = "signupAgree";
	}
	
	if(!document.formupdate.updatePreferredLang[0].checked && !document.formupdate.updatePreferredLang[1].checked)
    {
        showErrorInfo("updateErr-PreferredLang", GetRequiredText());
        errFocusField = "updatePreferredLang";
    }
	
    if(!document.formupdate.updateGender[0].checked && !document.formupdate.updateGender[1].checked)
    {
        showErrorInfo("updateErr-Gender", GetRequiredText());
        errFocusField = "updateGender";
    }
    
    if(month == "0" || day == "0" || year == "0")
	{
		showErrorInfo("updateErr-DOB", GetRequiredText());
		if(month == "00")
		    errFocusField = "updateMonth";
		else if(day == "0")
		    errFocusField = "updateDay";
		else
		    errFocusField = "updateYear";
	}
	else
	{    	
	    today = new Date();
	    birthDate = new Date(year, month - 1, day);    	    
	    var one_day = 1000*60*60*24;    	        	    
	    
	    var daysSinceBirth = Math.ceil((today.getTime()-birthDate.getTime())/(one_day));
	    if(daysSinceBirth < 4745)       //13 years
	    {
	        if(language == "EN")
	            showErrorInfo("updateErr-DOB", "&nbsp;must be 13+ years old");
            else
	            showErrorInfo("updateErr-DOB", "&nbsp;debes tener 13+ a&ntilde;os");
	            	    
	        errFocusField = "updateYear";
	    }
	}	
	
	if(lastName.length == 0)
	{
		showErrorInfo("updateErr-LastName", GetRequiredText());
		errFocusField = "updateLastName";
	}
	
	if(firstName.length == 0)
	{
		showErrorInfo("updateErr-FirstName", GetRequiredText());
		errFocusField = "updateFirstName";
	}
		
    if(errFocusField != null)
    {
        if(document.getElementById(errFocusField) != null)
        {                
            document.getElementById(errFocusField).focus();
        }
    }    
	return (errFocusField == null);	
}


function getTagValue(data, tag)
{
    var returnValue = null;
    var startTag = "<" + tag + ">";
    var endTag = "</" + tag + ">";
    
    var startPos = data.indexOf(startTag);        
    if(startPos >= 0)
    {
        returnValue = data.substr(startPos + startTag.length);
        returnValue = returnValue.substr(0, returnValue.indexOf(endTag));               
    }
    
    return returnValue;
}

function setSessionCookie(name, value, duration) 
{
    var cookiestring;
	
    if(duration != null)
        cookiestring = name+"="+escape(value)+";EXPIRES="+getexpirydate(duration) + ";path=/;domain=batanga.com;";
    else	
        cookiestring = name+"="+escape(value)+";path=/;domain=batanga.com;";
	
    document.cookie = cookiestring;
}

function getexpirydate(nodays)
{
    var UTCstring;
    Today = new Date();
    nomilli=Date.parse(Today);
    Today.setTime(nomilli+nodays*24*60*60*1000);
    UTCstring = Today.toUTCString();
    return UTCstring;
}

function getLanguage()
{
    //alert("getLanguage cookie hardcoded");
    //return "EN";
    
    var language =  getCookie("idioma");
    
    if(language  != null)
        language = language.toUpperCase();
    return language;
}

  // Returns a cookie value, given the name of the cookie:
function getCookie(Name) 
{
    var search = Name + "=" ;
	document.cookie.setDomain = "batanga.com";
	
	if (document.cookie.length > 0) 
	{ // if there are any cookies
		offset = document.cookie.indexOf(search)
		if (offset != -1 && offset != null) { // if cookie exists
			offset += search.length;
			// set index of beginning of value
			end = document.cookie.indexOf(";", offset);
			// set index of end of cookie value
			if (end == -1)
				end = document.cookie.length;
			return unescape(document.cookie.substring(offset, end));
		}
		
	}
	else
	{
		return null;
	}
}

function setupCookie(key, cookieName, data)
{
    var value = getTagValue(data, key);      
    if(value == null) return;
    
    if(cookieName == null)
        cookieName = key;
        
    //remove any <![CDATA[]]>  and just extract the data inside....
    var re = /(<!\[CDATA\[)(.+)(\]\]>)/;
    value = value.replace(re, "$2");
    
    if(batangaLoginDebug == 1)
        alert("setupCookie: cookieName=" + cookieName + ", value=" + value);               
        
    setSessionCookie(cookieName, value, null);        
}    

function updateElementsPositions()
{
     var dlg_background  = document.getElementById("modal-Background");
     if(dlg_background  != null && dlg_background.style.display != "none")
     {
     
        dlg_background.style.width = Math.max(document.documentElement.scrollWidth, document.body.scrollWidth) + "px";        
        dlg_background.style.height = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight) + "px";              
        
        var loginBox  = document.getElementById("modal-loginBox");         
        if(loginBox  != null && loginBox.style.display != "none")
        {                                
            loginBox.style.top = Math.max(document.documentElement.scrollTop, document.body.scrollTop) + offsetFromTop + "px";
            loginBox.style.left = ((document.body.clientWidth / 2) - (loginDialogWidth / 2)) + "px";
            loginBox.style.overflow = "hidden";
        }
     }
}

function resizeModalWindow()
{
    updateElementsPositions();
}

function scrollModalWindow()
{
    updateElementsPositions();
}


function addResizeEvent(func) 
{   
    var oldonResize = window.onresize;   
    if (typeof window.onresize != 'function') 
    {   
        window.onresize = func;   
    } 
    else 
    {   
        window.onresize = function() {   
            oldonResize();   
            func();   
        }   
    }
}   

function addScrollEvent(func) 
{       
    var oldonScroll = window.onscroll;   
    if (typeof window.onscroll != 'function') 
    {   
        window.onscroll = func;   
    } 
    else 
    {   
        window.onscroll = function() {   
            oldonScroll();   
            func();   
        }   
    }
}   


function CreateAJAXRequest()
{
    var http_request = null;
    
    if (window.XMLHttpRequest)
    { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) 
        {
            // set type accordingly to anticipated content type
            //http_request.overrideMimeType('text/xml');
            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) 
    {
        alert('Cannot create XMLHTTP instance');
        //return false;
    }
    
    return http_request;

}

function GetTagValue(data, tag)
{
    var startTag = "<" + tag + ">";
    var endTag = "</" + tag + ">";
    var returnValue = null;
    
    var startPos = data.indexOf(startTag);
    if(startPos >= 0)
    {
        returnValue = data.substr(startPos + startTag.length);
        returnValue = returnValue.substr(0, returnValue.indexOf(endTag));               
    }
    
    return returnValue;
}


addResizeEvent(resizeModalWindow);
addScrollEvent(scrollModalWindow);