/* 
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/


var map;
var isEnabled = false;
var isBuisy = false;
var http_request = null;
var timerID = 0;
var seconds = 15;
var consumer_location = null;
var doc
var pageSize = 10;
var pageinationSize = 5;
var searchTeen = false;
var searchPostCode = '';
var searchTown = '';


function pageLoad() {


    messageText = DocLocBoxTextList[getCurrentVariation()];
    
    var selectElement = document.getElementById("docloc_in_country");
       
         
    
         document.getElementById('docloc_in_adult').checked = false;
         document.getElementById('docloc_in_teen').checked = false;
               
       if (requestTeen == '1') {
            enable_address();
            searchTeen = true;
            document.getElementById('docloc_in_teen').checked = true;
        } else {
           if(requestTeen == '0' ) { // ie dont enable if not specified
               enable_address();
               searchTeen = true;
           document.getElementById('docloc_in_adult').checked = true;
           }
            searchTeen = false;
        }

        if (requestCountry != '') {

            for (idx = 0; idx < selectElement.options.length; idx++) {
                if (selectElement.options[idx].value == requestCountry) selectElement.selectedIndex = idx;
            }  
        }

        if (requestPostCode != '' && requestCountry != '') {
            if (requestTeen == '') {
                enable_address();
                searchTeen = false;
                document.getElementById('docloc_in_adult').checked = true;
            }
        this.isEnabled=true;
        document.getElementById("docloc_in_postcode").value = requestPostCode;
        getDocLoc(requestCountry, '', requestPostCode);
    }
        
}    

function doBackButton() {
// return "whlloworld";// false;
}

function clickme() {
    alert("You clicked the map.");
}

function animate() {
    map.panTo(new GLatLng(37.4569, -122.1569));
}


function popup() {
    map.openInfoWindow(map.getCenter(),
        document.createTextNode("Hello, world"));

}

function teen_click() {
    enable_address();
}

function adult_click() {
    enable_address();

}
function enable_address() {
    isEnabled = true;
    document.getElementById("docloc_in_town").disabled = false;
    document.getElementById("docloc_in_postcode").disabled = false;
    document.getElementById("docloc_in_country").disabled = false;

}
function doDocLocSearch() {

document.getElementById('search_button').blur()
    clearDocLocMessage();
    obj = document.getElementById('docloc_in_teen');
    this.searchTeen = obj.checked;

    if (isEnabled == true) {
        var town = document.getElementById("docloc_in_town").value;
        var postcode = document.getElementById("docloc_in_postcode").value;
        var selectElement = document.getElementById("docloc_in_country");
        var country = selectElement.options[selectElement.selectedIndex].value;

        var searchString;

        if (postcode != '') {
            searchString = postcode
        } else {
            if (town != '') {
                searchString = town
            } else {
                doDocLocMessage(getDocLocTextMessage('Please Specify town and or postcode'));
                return;
            }
        }
        searchString = searchString.replace(/ /g, '+');
        //    alert(country + searchString);
        //  GoogleLoc(country,searchString);
        getDocLoc(country, town, postcode);
    } else {
        doDocLocMessage(getDocLocTextMessage('Please select teen or adult search first'));
    }
  
}




function getGoogleLoc(country, search) {
    this.request = new Ajax.Request();


    url = 'http://localhost:3000/docservice/geocode.json?country=' + country + '&search=' + search

    this.request = new Ajax.Request(url,
    {
        method: 'get',
        onSuccess: function(transport, json) {
            var response = transport.responseText || "no response text";
            //alert("Success! \n\n" + response);
            var result = transport.responseText.evalJSON(true);
            googleLocRecieved(result);
        },
        onFailure: function() {
            alert('Something went wrong...')
            googleLocFailed()
        }
    });

}


function googleLocRecieved(loc) {

    this.consumer_location = loc;
    if (loc.Status.code != 200) {
        doDocLocMessage(getDocLocTextMessage('Address not Found'));
    } else {
        //alert('googleLocRecieved');
        Mlat = loc.Placemark[0].Point.coordinates[0];
        Mlong = loc.Placemark[0].Point.coordinates[1];
        //alert(Mlong);
        //alert(Mlat);
        map.setCenter(new GLatLng(Mlong, Mlat), 12);
    }
}


function googleLocFailed() {
    alert('gooogleLocFailed');
}


function getDocLoc(country, town, postcode) {


if(isBuisy  == false) {

    this.searchTown=town;
    this.searchPostCode=postcode;

    setBuisy(true);
    hideDiv("docloc_showdoc");
    hideDiv("docloc_showdoclist");
    hideDiv("docloc_top_pagebar");
    hideDiv("docloc_bottom_pagebar");
    hideDiv("docloc_annotation_key");

    if (this.searchTeen){
        teen='yes';
    }else {
        teen='no';
    }

    DoctorService.Search(encode(town),postcode,country,teen,onSearchComplete, onSearcheFailed);
}
} 


// Process the results.  
function onSearchComplete(result) {
    // result contains the JSON-serialized Location object.

    this.result = result;
    setBuisy(false);

    if (result.count > 0) {
        renderDoctorList(0, 10);
       
        firePageTracker('/DocLocSearchResults');
        fireFloodlightResults();
    } else {
      if(this.searchTeen == true) {
        doDocLocMessage(getDocLocTextMessage('No Doctors Found for this location teen'));
        } else {
        doDocLocMessage(getDocLocTextMessage('No Doctors Found for this location'));
        }
    }
 

}

function setBuisy(busy){
   if( busy == true){
    isBuisy = true;
    showDiv('docloc_buisy');
   }else{
     hideDiv('docloc_buisy');
    isBuisy = false;
   }
}
    
    
// Process the results.  
function onSearcheFailed(result) {
    // result contains the JSON-serialized Location object.
    alert('An error has occoured' + result);
    this.result = result;
    setBuisy(false);
            
    if (result.Doctors instanceof Array) {
        this.doctor_list = loc.DocLocResults.doctor;
    } else {
        this.doctor_list = Array();
        this.doctor_list[0] = loc.DocLocResults.doctor
    }

    if (loc.DocLocResults.doctor) {
        renderDoctorList(0, 10);
    } else {
        doDocLocMessage(getDocLocTextMessage('No Doctors Found for this location'));
    }


}


function doDocLocMessage(message) {
    var msg = document.getElementById("messages");
    msg.innerHTML = message;
}
function clearDocLocMessage() {
    var msg = document.getElementById("messages");
    msg.innerHTML = '&nbsp;';
}




function renderDoctorList(page) {
    //alert("doclist " +page);
    //alert(this.doctor_list.DocLocResults.doctor.size());


    output = '<table class="docloc_showdoclist" width="100%" cellpadding="2" cellspacing="1">';
    output += ' <tbody><tr>'
    output += '     <th class="docloc_showdoc">&nbsp;</th>'
    output += '     <th class="docloc_showdoc">' + getDocLocTextMessage('Invisalign provider name')+ '</th>'
    output += '     <th class="docloc_showdoc">' + getDocLocTextMessage('Address') + '</th>'
    if (!this.searchTeen) output += '     <th class="docloc_showdoc">' + getDocLocTextMessage('Designation')+ '</th>'
    output += '   </tr>'
    start = page * this.pageSize;
    end = (page + 1) * this.pageSize;
    for (count = start; (count < this.result.count && (count < end)); count++) {
        this.doc = this.result.Doctors[count];
        doc_name = '';
        doc_clinic = '';
        doc_street = '';
        doc_postcode = '';
        doc_town = ''
        doc_country = ''
        if (doc.name) doc_name = doc.name;
        if (doc.clinic) doc_clinic = doc.clinic;
        if (doc.street) doc_street = doc.street;
        if (doc.postcode) doc_postcode = doc.postcode;
        if (doc.town) doc_town = doc.town;
        if (doc.country) doc_country = doc.country;
        output += '    <tr>'

        output += '     <td  width="20" class ="docloc_showdoc_border" valign="top">' + (count + 1) + '</td>'


        output += '   <td width="185" class ="docloc_showdoc_border" valign="top"><b>' + doc_name + '</b></td>';
        if (!this.searchTeen) {
            output += '   <td width="260" class ="docloc_showdoc_border" valign="top">'
        } else {
            output += '   <td class ="docloc_showdoc_border" valign="top">'
        }

        output += doc_clinic + '<br>' + doc_street + '<br>'
        output += doc_postcode + ' ' + doc_town + ' ' + doc_country + '<br>';
        output += '   <a class="docloc_clickhear" href="#" onclick="showDoctor(' + count + ');" >' + getDocLocTextMessage('Click here for contact details')+ '</a></td>'


        if (!this.searchTeen) {
            output += '     <td   class ="docloc_showdoc_border" valign="top">'
            output += '      <table style="border: 0px none ; margin: 0px; padding: 0px;" cellpadding="0" cellspacing="0">'
            output += '        <tbody>'
            output += '          <tr style="border: 0px none ;">'

           // if (this.doc.Annotations.size() > 0 ) {
                output += renderAnotations(this.doc.Annotations);
           // }

            output += '     </tr></tbody>'
            output += '      </table>'
            output += '   </td>'
        }
        output += '   </tr>'

    }
    output += '    </tbody>';
    output += '  </table>';


    elmt = document.getElementById("docloc_showdoclist")
    elmt.innerHTML = output;

    showDiv("docloc_showdoclist");
    showDiv("docloc_annotation_key");
    renderPageination(page);
}

function renderPageination(page) {

    output = '';
    docCount = this.result.count;


    startPage = (page - (page  % (this.pageinationSize)));

    last = ((page * this.pageSize) + this.pageSize);
    if (last > docCount) last=docCount;
    stats = '' + ((page* this.pageSize)+1) + ' - ' + last + ' ';
    stats += getDocLocTextMessage('of')+ ' ' + docCount + ' ' + getDocLocTextMessage('search results in')
    if(this.searchPostCode == ''){
        stats += this.searchTown;
    }else {
        stats += getDocLocTextMessage('postal code area')+ this.searchPostCode;
    }
    
    if (page != 0){
         output += renderURL(getDocLocTextMessage('Previous'),page -1,true);
    }
    
    for (count = startPage; ((count < (startPage + this.pageinationSize)) && (count *  this.pageSize) < this.result.count); count ++) {
        if (count != page) {
            output += renderURL(count +1,count,true);
        } else {
            output += renderURL(count+1,count,false);
        }
    }
    
    // is there a next ?
    if (((page +1) * this.pageSize) < docCount) {
         output += renderURL(getDocLocTextMessage('Next'),page + 1,true);
    }

 
    elmt = document.getElementById("docloc_top_page_summary")
    elmt.innerHTML = stats;
    elmt = document.getElementById("docloc_bottom_page_summary")
    elmt.innerHTML = stats;
    elmt = document.getElementById("docloc_top_page_nav")
    elmt.innerHTML = output;
    elmt = document.getElementById("docloc_bottom_page_nav")
    elmt.innerHTML = output;


    showDiv("docloc_top_pagebar")
    showDiv("docloc_bottom_pagebar")

}

function renderURL(text, page, link) {
  if(link == true){
          return'<a class="docloc_pagination" href="#" onclick="renderDoctorList(' + page  + ')">' + text + '</a>&nbsp;';
    } else {
         return  '<span style="text-decoration: underline;" >' + text + '</span>&nbsp;';
    }
}

function renderAnotations(anno) {

    output = '';
    for (idx in anno) {
        akey = anno[idx];
        output += '           <td  class="docloc_annotation"  title="' + getDocLocTextMessage("annotation " + akey)+ '">';
        output += '           <img alt="'+ getDocLocTextMessage("annotation " + akey)+'" src="/images/' + annotationImage[akey] + '" border="0"></td>'
    }
    return output;
}


function showDoctor(docIdx) {

    this.doc = this.result.Doctors[docIdx];
    doc_name = '';
    doc_phone = '';
    doc_email = '';
    doc_website = '';
    doc_clinic = '';
    doc_street = '';
    doc_postcode = '';
    doc_town = '';
    doc_country = '';

    if (doc.name) doc_name = doc.name;
    if (doc.phone) doc_phone = doc.phone;
    if (doc.email) doc_email = doc.email;
    if (doc.website) doc_website = doc.website;
    if (doc.clinic) doc_clinic = doc.clinic;
    if (doc.street) doc_street = doc.street;
    if (doc.postcode) doc_postcode = doc.postcode;
    if (doc.town) doc_town = doc.town;
    if (doc.country) doc_country = doc.country;
    
    
    try{
        firePageTracker('/showdoctor/' + doc_name );
        fireFloodlightDoctorDetails();
              } catch(err){
       alert( err);
       }


    output = '<p>&nbsp;</p><div class="docloc_showdoctext">' + getDocLocTextMessage('Show Doc Text')+ '</div>';
    output += ' <table class="docloc_showdoc" width="100%" cellpadding="2" cellspacing="1">'
    output += ' <tbody><tr>'
    output += '     <th class="docloc_showdoc">' + getDocLocTextMessage('Invisalign provider name')+ '</th>'
    output += '     <th class="docloc_showdoc">' + getDocLocTextMessage('Address and Contact Details')+ '</th>'
    if (!this.searchTeen) {
        output += '     <th class="docloc_showdoc" style="width:180px;" >' + getDocLocTextMessage('Designation')+ '</th>'
    }
    output += '   </tr>'
    output += '   <!-- a doc -->'
    output += '   <tr>'



    output += '     <td width="200" class ="docloc_showdoc_border" valign="top"><b>' + doc_name + '</b></td>'
    if (!this.searchTeen) {
        output += '   <td  class ="docloc_showdoc_border" valign="top">'
    } else {
        output += '   <td class ="docloc_showdoc_border" valign="top">'
    }

    output += doc_name + '<br>' + doc_clinic + '<br>' + doc_street + '<br>';
    output += doc_postcode + ' ' + doc_town + ' ' + doc_country + '<br>';

    output += 'Phone: ' + doc_phone + '<br>Email: <a href="mailto:' + doc_email + '" onclick="firePageTracker(\'/email/'+ doc_email +'\');">' + doc_email + '</a><br>';
   output += 'Web: <a target="_new" href="http://' + doc_website + '" onclick="firePageTracker(\'/outgoing/' + doc_website  + ');" rel="nofollow">' + doc_website + '</a><br></td>'

    if (!this.searchTeen) {
        output += '     <td class ="docloc_showdoc_border" valign="top">'
        output += '       <table style="border: 0px none ; margin: 0px; padding: 0px;" cellpadding="0" cellspacing="0">'
        output += '         <tbody>'
        output += '           <tr style="border: 0px none ;">'

        
        output += renderAnotations(this.doc.Annotations);
        
        output += '      </tr></tbody>'
        output += '       </table>'
        output += '     </td>'
    }

    output += '   </tr>'
    output += '   <!-- end a doc -->'
    output += ' </tbody>'
    output += ' </table>'
    output += '<table width="100%" ><tr><td class="docloc_showdoc" style="text-align: right;"><input id="backbut" title="Back" alt="Back" onclick="backToList(); return false;" type="image"  src="' + getDocLocTextMessage("back_button_image")+ '" /></td></tr></table>'

    hideDiv("docloc_search_panel");

    elmt = document.getElementById("docloc_showdoc")
    elmt.innerHTML = output;

    hideDiv("docloc_showdoclist");
    hideDiv("docloc_top_pagebar");
    hideDiv("docloc_bottom_pagebar");
    hideDiv("docloc_annotation_key");
    showDiv("docloc_showdoc");
}


function backToList() {
    try {
    showDiv("docloc_search_panel");
    showDiv("docloc_showdoclist");
    showDiv("docloc_bottom_pagebar");
    showDiv("docloc_top_pagebar");
    showDiv("docloc_annotation_key");
    hideDiv("docloc_showdoc");
    }catch(e) {
        alert(e);
    }
}


function showDiv(id) {
    if (document.getElementById) {
        obj = document.getElementById(id);
        obj.style.display = "";
    }
}

function hideDiv(id) {
    if (document.getElementById) {
        obj = document.getElementById(id);
        obj.style.display = "none";
    }

}

function getDocLocTextMessage(key){
var message;
try {
    message = messageText[key];
    }
catch (error) {
    message = "Text key :" + key + ": not found for " + getCurrentVariation();
    alert(message);
    }
    return message;
}


function firePageTracker(event_url){

try{
  pageTracker._trackPageview(event_url);
 } catch(err) {
//     alert(err);
 }

}



function fireFloodlightResults(){

try{
var axel = Math.random() + "";
var a = axel * 10000000000000;
var flodDiv = document.getElementById("docloc_floodlight_div");
flodDiv.innerHTML = '<iframe src="http://fls.doubleclick.net/activityi;src=1464852;type=invis509;cat=finda474;ord=1;num=' + a + '?" width="1" height="1" frameborder="0"></iframe>';
} catch(err) {
alert(err);
}

}


function fireFloodlightDoctorDetails(){
try{
var axel = Math.random()+"";
var a = axel * 10000000000000;
var flodDiv = document.getElementById("docloc_floodlight_div");
flodDiv.innerHTML = '<iframe src="http://fls.doubleclick.net/activityi;src=1464852;type=invis509;cat=docto223;ord=1;num=' + a + '?" width="1" height="1" frameborder="0"></iframe>';
} catch(err) {
alert(err);

}
}



function encode(str) {
	var result = "";
	
	for (i = 0; i < str.length; i++) {
		if (str.charAt(i) == " ") result += "+";
		else result += str.charAt(i);
	}
	
	return escape(result);
}

