/**
 * Main map functions
 */
STREETVIEW  = function () {
    
    //global map object
    STREETVIEW.prototype.map;
    STREETVIEW.prototype.counter = 0; 
	
    //default map settings
    STREETVIEW.prototype.currentLat = 48.8583;
    STREETVIEW.prototype.currentLng = 2.2945;
    STREETVIEW.prototype.currentZoom = 6;
    STREETVIEW.prototype.currentView = null;
    STREETVIEW.prototype.panorama = null;
    STREETVIEW.prototype.cbp = null;
    STREETVIEW.prototype.sign = null;
     
    STREETVIEW.prototype.init = function() {
        
          //check if dom has been loaded or created
            try{
                document.getElementById('stview').innerHTML;
            }catch(e){            
                if (this.counter > 60) { 
                    alert('Can\'t load map! Can\'t find dom object!');
                } else { 
                    setTimeout("stview.init()", 1000); 
                    this.counter++;                
                } 
                return false; 
            }

            //If gmaps main.js didn't load try to call init again after 60 tries we give up
            if (typeof google.maps != "object") { 
                if (this.counter > 60) { 
                    document.getElementById('stview').innerHTML = 'Can\'t load streetview! Gmap server timeout! ';
                } else { 
                    setTimeout("stview.init()", 1000); 
                } 
                this.counter++; 
                return false; 
            }
            decodeUrl = window.location.search.substring(1).split('=');
           
            if(decodeUrl.length>1){
                 if(parseInt(decodeUrl[1])){ 
                     this.currentLat = parseFloat(decodeUrl[1]);   
                 }
                 if(parseInt(decodeUrl[2])){ 
                     this.currentLng = parseFloat(decodeUrl[2]); 
                 }  
                 if(parseInt(decodeUrl[3])) this.currentZoom = parseInt(decodeUrl[3]);
           
            }
                   
           this.panorama = new google.maps.StreetViewPanorama(document.getElementById("stview"));
           this.currentView = new google.maps.LatLng(this.currentLat, this.currentLng);
           //this.showLocation(this.currentView);
           
           //myPano.setVisible(true);
           if(this.panoid != null){
               this.setView(this.panoid,this.cbp);
           }else{
               stview.nextView(); 
           }
           this.reSizeView();
           if(this.sign != null) stview.setStSign(this.sign);
    }
    
    STREETVIEW.prototype.showLocation = function(loc) {
        var gService = new google.maps.StreetViewService();
        gService.getPanoramaByLocation(loc, 1000, function (data, status){
            if (status == google.maps.StreetViewStatus.OK) {
                stview.panorama = new google.maps.StreetViewPanorama(document.getElementById("stview"));
                
                //stview.panorama.setVisible(true);
                stview.panorama.setPano(data.location.pano);
                stview.panorama.setPov({heading: Math.floor(Math.random()*360), zoom: 1, pitch: 0});
                document.getElementById('nextbtn').innerHTML = "Next";
            }else {
                //stview.panorama.setVisible(false);
                setTimeout("stview.nextView()",500);
            }            
        });
    }
    
    STREETVIEW.prototype.nextView = function() {
        saveUrl = document.getElementById("saveurl");
        document.getElementById('nextbtn').innerHTML = '<img src="imgs/loading.gif" />';
        this.ajax('callback.php?filter='+stview.filter,stview.showNext);
        if(saveUrl.innerHTML.length>10) saveUrl.innerHTML = '';
    }
    
    STREETVIEW.prototype.ajax = function(url,action) {    
            try {
        		xmlhttp = window.XMLHttpRequest?new XMLHttpRequest(): new ActiveXObject("Microsoft.XMLHTTP"); 
        	} catch (e) { 
        		alert('Sorry! Your browser is too old. Please upgrade.\n\nVisit: mozilla.com/');
        	} 		
        	xmlhttp.onreadystatechange = action; 		
        	xmlhttp.open("GET", url, true); 		
        	xmlhttp.send(null);          
    }
    
    STREETVIEW.prototype.id = null;
    STREETVIEW.prototype.showNext = function(){
            if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) {
                //document.getElementById('notes').innerHTML = xmlhttp.responseText;
                results = xmlhttp.responseText.split("\;");
                stview.id = results[0];
                if(results.length>4){
                    if(results[1].length<1){
                        alert("Sorry, we couldn't find an image. Please change your filter selections and try again");
                        return false;
                    }
                   
                    stview.setView(results[3],results[4]);
                    stview.setStSign('<img src="imgs/flags/'+results[6]+'.png" width="16" /> ' + results[7] + ' - ' + results[5]);
                    
                }else{
                    stview.showLocation(new google.maps.LatLng(results[2],results[3])); 
                    stview.setStSign('<img src="imgs/flags/'+results[0]+'.png" width="16" /> ' + results[1] );
                }
            }
    }
    
    STREETVIEW.prototype.setStSign = function(text){
        if(text.length>0) document.getElementById("locationsign").style.display = "block";
        else document.getElementById("locationsign").style.display = "none";
        document.getElementById("locationsign").innerHTML = text;
        
    }
    
    
    STREETVIEW.prototype.setView = function(val,pov){
         var gService = new google.maps.StreetViewService();
         this.cbp = pov;
         gService.getPanoramaById(val, function (data, status){
                if (status == google.maps.StreetViewStatus.OK) {
                    stview.panorama = new google.maps.StreetViewPanorama(document.getElementById("stview"));
                    stview.panorama.setPano(val);  
                    if(stview.cbp != null){
                           //console.log(pov);
                           var tmp = stview.cbp.split(",");
                           var p = {heading:parseFloat(tmp[1]),zoom:parseFloat(tmp[3]),pitch:parseFloat(tmp[4])} 
                           stview.panorama.setPov(p);    
                       }                  
                    //stview.panorama.setVisible(true);
                     document.getElementById('nextbtn').innerHTML = "Next";
                }else {
                    //stview.panorama.setVisible(false);
                    setTimeout("stview.nextView()",1000);
                }            
        });
       
           
    }
    STREETVIEW.prototype.getCurrentView = function() {
             s = 'panoid=' + stview.panorama.getPano();
             pov = stview.panorama.getPov();
             s += '&cpb=1,' + pov.heading.toFixed(2) + ',,' + pov.zoom + ',' + pov.pitch.toFixed(2);
             return s;      
    }
    
    
    STREETVIEW.prototype.popup = function(id){
            document.getElementById('popup_content').innerHTML = "Loading ... ";
            document.getElementById('popup_box').style.display = 'block';
            this.ajax('popup.php?id='+id,stview.showPopup);
    }
    
    STREETVIEW.prototype.showPopup = function(){
        if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) {
            document.getElementById('popup_content').innerHTML = xmlhttp.responseText;
        }
    }
    
    STREETVIEW.prototype.getCurrentLink = function(){
        if(parseInt(stview.id)>0){
            return 'http://' + window.location.host + window.location.pathname + '?i=' + stview.id;
        }else{
            return 'http://' + window.location.host + window.location.pathname + '?'+ stview.getCurrentView();
        }
    }
    
    STREETVIEW.prototype.saveUrl = function (){
        saveUrl = document.getElementById("saveurl");
        if(saveUrl.innerHTML.length>10){
            saveUrl.innerHTML = '';
        }else{
            saveUrl.innerHTML = '<input size="35" type="text" value="'+ stview.getCurrentLink() + '" /> <a id="clipboard">Copy</a>';
            var clip = new ZeroClipboard.Client();
            clip.setText( stview.getCurrentLink());
        	clip.setHandCursor( true );
            clip.glue( 'clipboard' );        
        }
    }
   
    STREETVIEW.prototype.sendPage = function (){
        window.open('mailto:?subject=Check%20Out%20This%20streetview&body=Check%20out%20the%20following%20site:%0D%0D' + stview.getCurrentLink(),'ptm','height=450,width=675').focus();
    }
    
    STREETVIEW.prototype.recommend = function (){
        this.ajax('recommend.php?'+stview.getCurrentView() + '&lat='+stview.panorama.getPosition().lat() + '&lng='+stview.panorama.getPosition().lng(),null);
        document.getElementById('checklabel').style.display = 'block';
        setTimeout("document.getElementById('checklabel').style.display = 'none';",1000);
    }
    
    STREETVIEW.prototype.getCurrentView = function() {
          pov = stview.panorama.getPov();
          return "panoid=" + stview.panorama.getPano() + '&cbp=' + '1,' + pov.heading.toFixed(2) + ',,' + pov.zoom + ',' + pov.pitch.toFixed(2);      
     }
    
   
    STREETVIEW.prototype.filter = '';
    
    STREETVIEW.prototype.doFilter = function(val){
            var checkBoxList = document.getElementsByClassName('filterselect');
            stview.filter = '';
            for(checkbox in checkBoxList){
                if(typeof(checkBoxList[checkbox].id) == 'string'){
                    if(checkBoxList[checkbox].checked){
                        stview.filter += checkBoxList[checkbox].value + ",";
                    }
                }
            }
            stview.filter += '&' + val;
            stview.nextView();
            
    }
    
    STREETVIEW.prototype.reSizeView = function (){
      	var xScroll, yScroll;

      	if (window.innerHeight && window.scrollMaxY) {
      		xScroll = document.body.scrollWidth;
      		yScroll = window.innerHeight + window.scrollMaxY;
      	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
      		xScroll = document.body.scrollWidth;
      		yScroll = document.body.scrollHeight;
      	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
      		xScroll = document.body.offsetWidth;
      		yScroll = document.body.offsetHeight;
      	}

      	var windowWidth, windowHeight;
      	if (self.innerHeight) {	// all except Explorer
      		windowWidth = self.innerWidth;
      		windowHeight = self.innerHeight;
      	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
      		windowWidth = document.documentElement.clientWidth;
      		windowHeight = document.documentElement.clientHeight;
      	} else if (document.body) { // other Explorers
      		windowWidth = document.body.clientWidth;
      		windowHeight = document.body.clientHeight;
      	}

      	// for small pages with total height less then height of the viewport
      	if(yScroll < windowHeight){
      		pageHeight = windowHeight;
      	} else {
      		pageHeight = yScroll;
      	}

      	// for small pages with total width less then width of the viewport
      	if(xScroll < windowWidth){
      		pageWidth = windowWidth;
      	} else {
      		pageWidth = xScroll;
      	}
        //document.getElementById('container').style.width =  (pageWidth-100) + 'px';
        document.getElementById('stview').style.width =  (pageWidth-460) + 'px';
    }

    
    
    
 
}

var stview = new STREETVIEW;

window.onresize = function(){
    stview.reSizeView();
}

window.onload = function(){
    stview.reSizeView();
}

if(typeof(document.getElementsByClassName) != "function"){
    
    function getElementsByClass(searchClass,node,tag) {
            var classElements = new Array();
            if ( node == null )
                    node = document;
            if ( tag == null )
                    tag = '*';
            var els = node.getElementsByTagName(tag);
            var elsLen = els.length;
            var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
            for (i = 0, j = 0; i < elsLen; i++) {
                    if ( pattern.test(els[i].className) ) {
                            classElements[j] = els[i];
                            j++;
                    }
            }
            return classElements;
    }

    document.getElementsByClassName = getElementsByClass;
}


