var currentPage = "";
var externalFipStage = 1;
var bookingEngine_ = -1;
var externalId_ = -1;
var businessId_ = -1;
var refId_ = -1;
var current = 0;

/*
 *deprecated.
 **/
function switchit(div, dimage, dtext)   {
    var listElement = document.getElementById(div);
    var listElementStyle=document.getElementById(div).style;
    var image = document.getElementById(dimage);
    var text = document.getElementById(dtext);
    if (listElementStyle.display=="none"){
        listElementStyle.display="block";
        image.innerHTML = '<img src="/images/main/arrowup.gif" border="0px" width="20px" height="20px" alt="arrow"/>';
        text.innerHTML = 'Click to hide all locations ';
/*
        var seoDiv = document.getElementById("toggleText");
        var textToInclude = "";
        var allsubElements = listElement.getElementsByTagName("span");
       
        for(var i = 0;i<7;i++){
            if ( allsubElements[i].getAttribute('name') == "businessAddress" ){
                textToInclude = textToInclude + allsubElements[i].innerHTML + "<br/> ";
            }
        }

        seoDiv.innerHTML = "<p>" + textToInclude + "</p>";
*/
    }
    else {
        listElementStyle.display="none";
        image.innerHTML = '<img src="/images/main/arrowdown.gif" border="0px" width="20px" height="20px" alt="arrow"/>';
        text.innerHTML = 'Click to see all locations ';
    }
}

function showInfo(index){
    showMarkerInfo(index);      //in fsf.js
}

function closeInfo(index){
    closeMarkerInfo(index);
}

function ajaxFunction(method,url, divId,type) {
    var xmlHttp;
    try
    {
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    }
    catch ( e )
    {
        // Internet Explorer
        try
        {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch ( e )
        {
            try
            {
                xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch ( e )
            {
                alert("Your browser does not support AJAX!");
                return false;
            }
        }
    }
    xmlHttp.open(method,url,true);
    xmlHttp.send(null);
    xmlHttp.onreadystatechange=function()
    {
        if(xmlHttp.readyState==4)
        {
            if (( type == "FIP") || (type == "CONF")) {
                top.document.getElementById(divId).innerHTML=xmlHttp.responseText;

            } else if ( type == "MSG" ) {
                if ( xmlHttp.responseText.indexOf('NOPhone') == -1 ) {
                    var layer4 = top.document.getElementById(divId);
                    layer4.style.display = "block";
                    top.document.getElementById(divId).innerHTML=xmlHttp.responseText;
                }
                else {
                    unfreezeBackGround();
                }
            } else if ( type == "SEARCH"  || type == "filter") {

                document.getElementById(divId).innerHTML=xmlHttp.responseText;  //get listing...
                /*second Part... adding the map...*/
                var The_div = "createMarkersDiv";
                var url2 = baseDomain() + "/updateMap.html";

                ajaxUrl = url;
             

                /*check if browser is IE lower than 8.0*/
                var version=-1;
                if (navigator.appName == 'Microsoft Internet Explorer'){
                    var ua = navigator.userAgent;
                    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
                    if (re.exec(ua) != null)
                    version = parseInt( RegExp.$1 );
                }
                //if version = -1 -> browser is not IE
                //if version < 8 and > 0 reload the page
                if(0<version && version<8){
                    window.location.href=window.location.href;
                }/*/check if browser is IE lower than 8.0*/
                else{
                var aneee = new Ajax.Updater(The_div,url2,
		{
			evalScripts:true
		});
                }
                
            } else {
                document.getElementById(divId).innerHTML=xmlHttp.responseText;
            }            
            if (type != "MSG") {            
                hideClock();
            }

            if ( type == "FIP"){
                freezeBackGround();
                onloadFunctionFip();
            } else if (type == "CONF") {
                freezeBackGround();
                loadMap("mapbox");


            } else if (type == "RES") {
                freezeBackGround();
                loadCalendarForReservation();
                //addCalendar();
            } //else {
                //createMarkers();
            //}

            var leftpos = top.document.getElementById("leftPosition");
            if (leftpos != null ){
                top.document.getElementById("layer1").style.left = leftpos.value + "%";
            }

        } 
    }    
}

function baseDomain()
{
	
	/*
    url_site     = document.location.href;
    url_pos      = url_site.indexOf('//');
    url_limpia   = url_site.substr(url_pos+2);
    url_prot     = url_site.substr(0,url_pos+2);
    url_split    = url_limpia.split('?');
    url_base     = url_prot + url_split[0];

    url_fsf = url_base.split("FindStorageFast"); //+ "FindStorageFastLocalSource"
    url_ret = url_fsf[0];
    url_ret = url_ret.split("mainContent.html")[0];
    url_ret = url_ret.split("/partners/apartmentfinder.html")[0];// I have to test it with apartament finder
    url_ret = url_ret.split("#")[0];

    return url_ret;
    */
	var url     = document.location.href;
	var hostName = url.match(/(.*):\/\/(.[^/]+)/)[2];
	var protocolName = url.match(/(.*):\/\/(.[^/]+)/)[1];
	return protocolName + "://" + hostName;
}

function addDays(date, days){
    var milisec= parseInt(days *24*60*60*1000);
    date.setTime(date.getTime()+ milisec);
    return date;
}

function validateFields() {
    if (document.getElementById("FirstName").value == "") {
        alert("You must complete first name.");
        return false;
    }
    if (document.getElementById("LastName").value == "") {
        alert("You must complete last name.");
        return false;
    }
    if (document.getElementById("Email").value == "") {
        alert("You must complete e-mail.");
        return false;
    }
    if (document.getElementById("Phone").value == "") {
        alert("You must complete phone.");
        return false;
    }
    var Sdate = document.getElementById("Sdate").value;
    if (Sdate == "") {
        alert("You must complete date.");
        return false;
    }
    if (new Date(Sdate).toString() == "Invalid Date") {
        alert("Invalid date.");
        return false;
    }

    var dateIn60 = addDays(new Date(), 60);
    var reservation_date = new Date(Sdate);
    if (reservation_date < new Date()) {
        alert("Invalid date.");
        return false;
    }
    if (reservation_date > dateIn60) {
        alert("You can book at most 60 days after the current date.");
        return false;
    }
    return true;
}

function completeReservation(businessId, SScode, climate) {

    var Fname = document.getElementById("FirstName").value;
    var Lname = document.getElementById("LastName").value;
    var Email = document.getElementById("Email").value;
    var Phone = document.getElementById("Phone").value;
    var Sdate = document.getElementById("Sdate").value;
    if ( validateFields()) {
        var submitUrl = "/request_quote_save.html"
                            +"?businessId="+businessId
                            +"&firstName="+Fname
                            +"&lastName="+Lname
                            +"&phone="+Phone
                            +"&email="+Email
                            +"&dateNeeded="+Sdate
                            +"&storageSizeCode="+SScode+"-"+climate
                            +"&message="+"No message"
                        ;
 
        var destinationDivId = "layer3"; 
        ajaxDivId = destinationDivId;
        ajaxUrl = submitUrl; 
        updateAnalytics("/request_quote_analytics.html",businessId );        
        submitUrl=baseDomain() + submitUrl; 
        ajaxFunction("POST",submitUrl, ajaxDivId,"CONF");
        if ( isBrowserIE() ){
            idPastHistory = "conf";
            document.getElementById('searcher').src = "/CONF.html#" + idPastHistory;
        } else {
            document.location=document.location.toString().split('#')[0]+"#"+ "CONF";
            document.location=document.location.toString().split('#')[0]+"#";
        }
        destroyDivContent("layer2");
        showClock();
    }    
}

function displayFip(businessId, fipType) {

  if (fipType != 1) {
        var submitUrl = "/microsite.html"+"?businessId="+businessId+"&fipType="+fipType;
        var destinationDivId = "layer1";
        
        ajaxDivId = destinationDivId;
        ajaxUrl = submitUrl;
        updateAnalytics("/facility_details_analytics.html", businessId);
        submitUrl=baseDomain() + submitUrl;
        
        showClock();
        ajaxFunction("POST",submitUrl, ajaxDivId,"FIP");


        /*  code to track navegability using ajax   */
        if ( isBrowserIE() ){
            //alert("ie");
            idPastHistory = "fip2";
            document.getElementById('searcher').src = "/FIP2.html#" + idPastHistory;
        } else {
            document.location=document.location.toString().split('#')[0]+"#"+ "FIP2";
            document.location=document.locdocument.locationation.toString().split('#')[0]+"#";
        }
    }    
}

function displayExternalFip(bookingEngine, externalId, businessId, refId) {

    bookingEngine_ = bookingEngine;
    externalId_ = externalId;
    businessId_ = businessId;
    refId_ = refId;

    freezeBackGround();
    var layer1 = top.document.getElementById('layer1');
    var divxend = top.document.getElementById('xend2');
    var iframe = top.document.createElement('iframe');

    updateAnalytics("/facility_details_analytics.html", businessId);    
    iframe.id = "ifsf1";
    iframe.name = "ifsf1";
    iframe.src = 'http://www.buildmymove.com/Portals/Programs/SelfStorage/FindStorageFast/StorageDetails.aspx?storage='+externalId+'&id='+bookingEngine+'&ref='+refId;
    iframe.style.width = "900px";
    iframe.style.height = "2700px"
    iframe.style.left = "8px";
    iframe.style.position = "relative";
    iframe.style.top = "-50px";
    iframe.style.overflow = "hidden";       //hidden auto inherit scroll visible
    iframe.allowtransparency = "true";
    iframe.setAttribute("allowtransparency", "true");
    iframe.frameborder = "0";

    layer1.appendChild(iframe);
    divxend.onclick = function() {destroyIframeLayer1(businessId);};
    divxend.style.display = "block";
    divxend.style.zIndex = 200;
    externalFipStage = 1;

    /********   autoadjust iframe heigth    *********/

    /************************************************/

    /*  code to track navegability using ajax   *****/
    if ( isBrowserIE() ){

        idPastHistory = "fip1";
        document.getElementById('searcher').src = "/FIP1.html#" + idPastHistory;
    } else {

        document.location = document.location.toString().split('#')[0]+"#"+ "FIP1";
        document.location = document.location.toString().split('#')[0]+"#";
    }
    /************************************************/
}

function goToStep(step) {

    externalFipStage = step%4;
    var divxend = top.document.getElementById('xend2');
    if (externalFipStage == 1) {
        divxend.style.backgroundImage = "url('/images/button_go_back_to_map.png')";
        divxend.style.left = '13%';
    }
    else if (externalFipStage == 2) {

        divxend.style.backgroundImage = "url('/images/button_go_back.png')";
        divxend.style.left = '20%';

    }
    else if (externalFipStage == 3) {
        divxend.style.backgroundImage = "url('/images/button_go_back_to_map.png')";
        divxend.style.left = '20%';
    }
}

function nextStep () {

    goToStep(++externalFipStage);
}

function recreateLayer1() {    
    var layer1 = top.document.getElementById('layer1');
    var divxend = top.document.createElement('divxend');
    divxend.id = "xend2";
    divxend.style.backgroundImage = "url('/images/button_go_back_to_map.png')";
    //divxend.style.borderBottomWidth = '0';
    divxend.style.display = 'none';
    //divxend.style.borderTopWidth = '0';
    divxend.style.position = 'fixed' ;
    divxend.style.height = '33px';
    //divxend.style.paddingBottom = '0';
    divxend.style.paddingTop = '0';
    divxend.style.width = '181px';
    divxend.style.top = '0%';
    divxend.style.left = '13%';
    divxend.style.cursor = 'pointer';
    divxend.style.zIndex = 200;

    layer1.appendChild(divxend);    
}

function destroyIframeLayer1(businessId) {

    var layer1  = top.document.getElementById('layer1');
    var iframe  = top.document.getElementById('ifsf1');
    var divxend = top.document.getElementById('xend2');
    divxend.style.display = "none";    
    if ( iframe != null ) {
        layer1.removeChild(iframe);
    }
    var url = iframe.src;
    if ( externalFipStage == 1 ) {
        displayMessageBox(businessId);
    }
    else if ( externalFipStage == 2 ) {
        goToStep(1);
        displayExternalFip( bookingEngine_, externalId_, businessId_, refId_ );
    }
    else if ( externalFipStage == 3) {
        unfreezeBackGround();
    }
}

function displayMessageBox(businessId) {

    var submitUrl = "/messagebox.html"+"?businessId="+businessId;
    var destinationDivId = "layer4";

    ajaxDivId = destinationDivId;
    ajaxUrl = submitUrl;
    submitUrl= baseDomain() + submitUrl;
    ajaxFunction("POST",submitUrl, ajaxDivId,"MSG");
}

function closeMessageBox() {
    var layer4 = top.document.getElementById('layer4');
    layer4.style.display = "none";
    unfreezeBackGround();
}


function destroyDivContent(div){

    var divv = top.document.getElementById(div);
    divv.innerHTML = "";
    recreateLayer1();
    onDelete(currentPage);
    unfreezeBackGround();
}

function placeIt(obj)
{
        var x = 20;
        var y = 70;
	obj = document.getElementById(obj);
	if (document.documentElement)
	{
		theLeft = document.documentElement.scrollLeft;
		theTop = document.documentElement.scrollTop;
	}
	else if (document.body)
	{
		theLeft = document.body.scrollLeft;
		theTop = document.body.scrollTop;
	}
	theLeft += x;
	theTop += y;
	obj.style.left = theLeft + 'px' ;
	obj.style.top = theTop + 'px' ;
	setTimeout("placeIt('layer1')",500);
        window.onscroll = setTimeout("placeIt('layer1')",500);
}

function showMap(latitude, longitude,divId) {

    if (GBrowserIsCompatible()) {
        if (top.document.getElementById(divId) != null) {
            var map = new GMap2(top.document.getElementById(divId));
            map.setCenter(new GLatLng(latitude, longitude), 13);
            var latlng = new GLatLng(latitude, longitude);
            map.addOverlay(new GMarker(latlng));
        }
    }    
}

function loadMap(div){
    var lat = top.document.getElementById("fip_latitude").value;
    var longitude = top.document.getElementById("fip_longitude").value;

    showMap(lat, longitude,div);
}

function loadReservation(businessId, storageSizeId, isClimateControlled) {

    destroyDivContent("layer1"); //Carlos    
    var submitUrl = "/reservation.html"
                    +"?businessId="+businessId
                    +"&storageSizeId="+storageSizeId
                    +"&isClimateControlled="+isClimateControlled
                    ;

    var destinationDivId = "layer2";    
    ajaxDivId = destinationDivId;
    ajaxUrl = submitUrl;

    submitUrl=baseDomain() + submitUrl;
    ajaxFunction("POST",submitUrl, ajaxDivId, "RES");
    if ( isBrowserIE() ){
        idPastHistory = "res";
        document.getElementById('searcher').src = "/RES.html#" + idPastHistory;
    } else {
        document.location=document.location.toString().split('#')[0]+"#"+ "RES";
        document.location=document.location.toString().split('#')[0]+"#";
    }
}

function onDelete(type){

    if (type != "undefined"){
        if (type == "FIP" && currentLoadingGallery != null){
            onUnloadFunctionFip();
        }
    }
    currentPage = "";
}

var currentGalleryPosition = 0;
var currentLoadingGallery = null;

function getNextValue(gallery){

    if (++currentGalleryPosition >= gallery.length){
        currentGalleryPosition = 0;
    }
    return currentGalleryPosition;
}

function getValueBefore(gallery){

    if (--currentGalleryPosition < 0){
        currentGalleryPosition = gallery.length-1;
    }
    return currentGalleryPosition;
}

function nextGalleryImage(){
    var images = top.document.getElementsByName("galleryImage");
    if (images != null && images.length > 0){
        images[currentGalleryPosition].style.display = "none";
        images[getNextValue(images)].style.display = "inline";
    }
}

function beforeGalleryImage(){
    var images = top.document.getElementsByName("galleryImage");
    if (images != null && images.length > 0){
        images[currentGalleryPosition].style.display = "none";
        images[getValueBefore(images)].style.display = "inline";
    }
}

/**
 * function called when the fip page is displayed...
 */
function onloadFunctionFip(){

    currentPage = "FIP";
    currentGalleryPosition = 0      //inicialized when a new fip page is loaded.
    loadMap("mapdiv");                      //this is to load the map of the location...
    var time = 3000;                // 1000 ms = 1 second.
    currentLoadingGallery = setInterval(nextGalleryImage, time);
    nextGalleryImage();
    //hideClock();
}

function onUnloadFunctionFip(){
    window.clearInterval(currentLoadingGallery);
    //alert("cleared interval");
}

function freezeBackGround() {
    //alert("freeze background");
    var tool_tipDiv = top.document.getElementById("tool_tip");
    var stylee = tool_tipDiv.style;
    tool_tipDiv.className =  "tool_tip_class";
    stylee.display = "block";
    stylee.position = "fixed";
    stylee.left = 0;
    stylee.top = 0;
    stylee.width = "100%";
    stylee.height = "100%";
    stylee.zIndex = 100;
    stylee.backgroundColor  = "gray";
    stylee.opacity = 0.6;
}

function transparentFreezeBackGround() {    
    var tool_tipDiv = top.document.getElementById("tool_tip");
    var stylee = tool_tipDiv.style;
    tool_tipDiv.onclick = function() {displayHideFacilityOwners();};
    stylee.display = "block";
    stylee.position = "fixed";
    stylee.left = 0;
    stylee.top = 0;
    stylee.width = "100%";
    stylee.height = "100%";
    stylee.zIndex = 100;
    stylee.backgroundColor  = "";
    stylee.opacity = 0;
}

function transparentunFreezeBackGround() {
    unfreezeBackGround();
}

function unfreezeBackGround() {

    var tool_tipDiv = top.document.getElementById("tool_tip");
    if (tool_tipDiv != null){
        tool_tipDiv.style.display = "none";
    }
}

function showClock(){

    var tool_tipDiv = top.document.getElementById("tool_tip"); //top
    tool_tipDiv.className =  "tool_tip_class";
    var stylee = tool_tipDiv.style;
    stylee.display = "block";
    stylee.position = "fixed";
    stylee.left = 0;
    stylee.top = 0;
    stylee.width = "100%";
    stylee.height = "100%";
    stylee.zIndex = 350;
    stylee.backgroundColor  = "gray";
    stylee.opacity = 0.6;
    var clockImage = top.document.createElement("img");
    clockImage.id = "clcokImage";
    clockImage.src = "/images/waiting.gif"; //FindStorageFast/
    clockImage.style.left = "50%";
    clockImage.style.top = "50%";
    clockImage.style.position = "absolute";
    clockImage.style.opacity = 0.6;
    tool_tipDiv.appendChild(clockImage);
}

function hideClock(){
    
    var tool_tipDiv = top.document.getElementById("tool_tip");
    var clcok = top.document.getElementById("clcokImage");
    if (tool_tipDiv != null){
        if (clcok != null){
            tool_tipDiv.removeChild(clcok);
        }
        tool_tipDiv.style.display = "none";
    }
}

function displayHideFacilityOwners() {
    var div5 = top.document.getElementById("layer5");
    if (div5 != null) {
        if (div5.style.display == "none") {
            transparentFreezeBackGround();
            div5.style.display = "block";
        }
        else {
            transparentunFreezeBackGround();
            div5.style.display = "none";
        }
    }
}

function displayFacilityOwners() {    
    var div5 = top.document.getElementById("layer5");
    if (div5 != null) {
        
    }
}

function hideFacilityOwners() {
    var div5 = top.document.getElementById("layer5");
    if (div5 != null) {
        div5.style.display = "none";
    }
}

function showLocations(divId, imgId, spanId) {

    var div = document.getElementById(divId);
    var img = document.getElementById(imgId);
    var span =document.getElementById(spanId);
    if (div == null) {
        div = document.getElementById('toggleText');
    }
    if (div != null && img != null) {
        if (div.style.display == 'none' || div.style.display == '') {           
            div.style.display = 'block';
            img.src = '/images/main/arrowup.gif';
            span.innerHTML = 'Click to hide all locations ';
            div.id = 'toggleText';
            captureAnalyticEvent("Analytics","See_all_locations_Open");
        } else {
            div.style.display = 'none';
            img.src = '/images/main/arrowdown.gif';
            span.innerHTML = 'Click to see all locations ';
            div.id = 'all_locations'+imgId.split('arrow')[1];
            captureAnalyticEvent("Analytics","See_all_locations_Hide");
        }
    }
}

function switchPhone(spanId, phone) { 
    var span = document.getElementById(spanId);
    if (span != null) {
        if (span.innerHTML == 'Phone') {
            span.innerHTML = phone;
            var businessId;
            if (spanId.indexOf('map') == -1) {
                businessId = spanId.split('phonespan')[1];
            }
            else {
                businessId = spanId.split('phonespanmap')[1];
            }            
            updatePhoneAnalytics(businessId);
        }
    }
}


