/*
             Extend mootools' Ajax to allow queeing of  requests.
*/


Ajax = Ajax.extend({
 
    initialize: function( url, options ) {
        this.parent( url, options );
        this.ready = false;
        this.output = '';
    },
 
    onComplete: function() {
        this.ready = true;
        this.parent();
    }
 
});


/*
             Extend Native javascript functions.
*/


Function.prototype.method = function(name, func) {
	this.prototype[name] = func;
	return this;
}

Array.method('inArray', function(value) {
  if(Array.inArray) return;
  
  for ( var i = 0; i < this.length; i++ ) {
		if ( this[i] === value ) {
			return true;
		}
	}
	return false;
});

String.method('removeSpaces', function(string){
 return this.split(' ').join('');
});


/*
            Our Map Application begins here.
*/

var ERRORS = [];

var SANP_MAP = {
	
	current: false,
	
    mapImages:  $$("#mapDiv img"),
    
    Cache: {},
	
	
    getData: function(url, targetDiv, cache_key) {
	  var AJAX_QUEUE = [],
	      AjaxCall = new Ajax( url, {
		    method: 'get',
		    onComplete: function(response) { 
			  this.output = response;
			  
			  while ( AJAX_QUEUE.length ) {
			    if ( !AJAX_QUEUE[0].ready ) break;
				var current = AJAX_QUEUE.shift();
				if ( !AJAX_QUEUE.length ) {
		          var data = ( current.output ) ? current.output : 'Preferred Stockists not available in that province.';
		            if (cache_key) SANP_MAP.Cache[cache_key] = data;
                      $(targetDiv).empty().setHTML(data);
                }
			  }	
			}
		 });
	   
	  AJAX_QUEUE.push(AjaxCall);
	  AjaxCall.request();
	},
	
	
    addEvents: function() {
	  var imgs = SANP_MAP.mapImages, i;
	  
	    for(i = 0; i < imgs.length; i++){
	       imgs[i].onmouseover = function() {
		     this.src=this.src.replace("land","roll");
		   };
		  
	       imgs[i].onmouseout = function() {
		     this.src=this.src.replace("roll","land");
		   };
		  
	       imgs[i].onclick = function() {
		     var b = SANP_MAP.current;
			 
		     $('targetDiv1').empty().setHTML('<img src="http://www.sanatural.co.za/media/images/map/loading.gif" />');
			 
			 if ( b && b!=this.name ) document.images[b].src=document.images[b].src.replace("state","land");
			     this.src=this.src.replace("roll","state");
	             var handle = this.alt.toLowerCase();
				
	         if ( SANP_MAP.Cache[handle] ) {
	           new Fx.Style('targetDiv1', 'opacity', {wait:false}).set(0).start(1);
	           $("targetDiv1").empty().setHTML(SANP_MAP.Cache[handle]);
	            $("targetDiv").empty()
	         } 
			 else {
               SANP_MAP.getData("http://www.sanatural.co.za/app/app.php?prov="+this.alt,"targetDiv1",handle);
	         }
			
            SANP_MAP.current = this.name;
			_gaq.push(['_trackEvent', this.alt, 'clicked']);
            document.title = "Preferred Stockists - " + this.alt;
			
            return false; 
          };
		};
	}
	
};

SANP_MAP.createCache = {

  data: {},
  

  forCities: function() {
    var rows = SANP_MAP.createCache.data.query.results.row, provinces = []; 
		
    SANP_MAP.Cache['limpopo'] = "* Data for Northern Cape is not available. Please contact SANP head office - Tel: 031 783 8000";
    SANP_MAP.Cache['northern cape'] = "* Data for Limpopo is not available. Please contact SANP head office - Tel: 031 783 8000";
  
    for ( var i=1; i<rows.length; i++ ) {       // pull out all provinces
      if ( !provinces.inArray(rows[i].province) ) {
        provinces.push(rows[i].province);
      }	 
    }

    for ( var c = 0; c < provinces.length; c++ ) {
      var prov = provinces[c],
      cit_arr=[],
 	  cities =  '<form id="form1" name="form1" method="GET" >'+"\n";  
      cities +='<span>'+prov+'</span><select id="opts" name="opts" onchange="dDowm(); return false;">'+"\n";
      cities +='<option value="">Select your city</option>'+"\n";
  
      for ( var z = 1; z < rows.length; z++ ) {
        if ( rows[z].province === prov && !cit_arr.inArray(rows[z].city) ){
          cit_arr.push(rows[z].city); 
	    }
      }
	  
      cit_ar = cit_arr.sort();
	
      for ( var h = 0; h < cit_ar.length; h++ ) {
	    cities +='<option value="'+cit_ar[h]+'">'+cit_ar[h]+'</option>'+"\n";
	  }
	
      cities+="</select>\n</form>";
    
      SANP_MAP.Cache[prov.toLowerCase()] = cities;  	
    }
  }, 

  
  forStores: function() {
    var rows = SANP_MAP.createCache.data.query.results.row,
          city = [],  // holds all cities
          city_stores = {};  // holds all stores per city

    try{           
      for ( var i = 1; i < rows.length; i++ ) {
        if ( !city.inArray(rows[i].city) ) {  // if the city has not been added to array
          city.push(rows[i].city);        // add city to cities array.
          city_stores[rows[i].city] = []; // also add that city as a propery of city_stores object that holds an array.
        }	 
      }

      for ( var c = 0; c < city.length; c++ ) {  // loop over all cities 
        for( var i = 1, name = city[c]; i < rows.length; i++ ) { // loop the yahoo results array
          if ( rows[i].city == name ) {    // everytime you see a city that matches this city
            var stores =  '<div class="cDiv">'; // add a div
            stores +='<div class="cleft">Store:</div><div class="cright">'+rows[i].store+'</div> \n'; //that hold store name
            stores +='<div class="cleft">Address:</div><div class="cright">'+rows[i].address+'</div> \n'; // adress
            stores +='<div class="cleft">Manager:</div><div class="cright">'+rows[i].manager+'</div> \n';  //
            stores +='<div class="cleft">Phone:</div><div class="cright">'+rows[i].phone+'</div> \n';
            stores +='<div class="cleft">Fax:</div><div class="cright">'+rows[i].fax+'</div> \n';
            stores +='<div class="cleft">Email:</div><div class="cright"><a href="mailto:'+rows[i].email+'">'+rows[i].email+'</a></div> \n';
            stores +='<div class="cleft">Website:</div><div class="cright"><a href="'+rows[i].website+'">'+rows[i].website.replace('http://-', '-')+'</a></div>';
            stores+='</div><div class="space" style="width:685px; height:20px"><hr /></div>';
            city_stores[city[c]].push(stores);	// add that store info to the city property.
          }
        } 
		
        city_stores[city[c]].sort(); // sort the sores in this city
        var key = name.toLowerCase(), // create a key for the cache 
            my_output='', h;  // cache output
	    for ( h = 0; h < city_stores[city[c]].length; h++ ) { // loop this city array
	      my_output += city_stores[city[c]][h];   // concat 
	    }
		
        SANP_MAP.Cache[key] = my_output;   
      }
    } catch(e) {
	    ERRORS[0] = e;
	  }
  }  
};


/*
                                      Functions
*/


function showCits( o ) {
  SANP_MAP.createCache.data = o;
  SANP_MAP.createCache.forCities();
  window.setTimeout(showStores, 2000);
}


function showStores(){
	SANP_MAP.createCache.forStores();
}


function getData(a, b, c) {
  SANP_MAP.getData(a, b, c);
}


function removeSpaces(string) {
  return string.split(' ').join('');
}


function dDowm() {
  var a=$("opts"), b=$("provopts"), c='<img src="http://www.sanatural.co.za/media/images/map/loading2.gif">';

  if ( a ) {
    var r = a.options[a.selectedIndex].value, key = r.toLowerCase();
	
    $("targetDiv").innerHTML=c;
    
    if( SANP_MAP.Cache[key] ) {
      new Fx.Style('targetDiv', 'opacity', {wait:false}).set(0).start(1);
      $("targetDiv").empty().setHTML(SANP_MAP.Cache[key]);
    } 
	else {
      getData("http://www.sanatural.co.za/app/app.php?opts="+r,'targetDiv', key);
    }
  } 
  
  else {
    $("homediv").innerHTML=c;
    var t=b.options[b.selectedIndex].value;
    var hand = t.toLowerCase();
    if ( SANP_MAP.Cache[hand] ) {
      new Fx.Style('homediv', 'opacity', {wait:false}).set(0).start(1);
      $("homediv").empty().setHTML(SANP_MAP.Cache[hand]);
    } 
	else {
      getData("http://www.sanatural.co.za//app/app.php?provopts="+t, 'homediv', hand);
    }
  }
} 


/*  
                                       All event handlers 
*/


window.addEvent('domready', function(){
  var v = $("top_link"), h = document.links;
	
  for ( var i=0 ; i < h.length; i++ ) {
	h[i].href = h[i].href.replace("http://sanatural","http://www.sanatural");
  }	
	
  if ( v ) {
	$('top_link').addEvent('click', function(){
	  new Fx.Scroll(window).toTop();
    });
  }		
    SANP_MAP.addEvents();
});

window.addEvent('scroll', function() {
  if (!(document.all && !window.opera && !window.XMLHttpRequest)) {
	try {
	  var el = $("scroll"), pos = 0;
		
	    if ( typeof( window.pageYOffset ) == 'number' ) {
	        pos = window.pageYOffset;
	    } 
		else if ( document.body && (document.body.scrollLeft || document.body.scrollTop ) ) {
	      pos = document.body.scrollTop;
	    } 
		else if ( document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop) ) {
	      pos = document.documentElement.scrollTop;
	    }

      if ( pos > 400 ) {   
	    el.setStyle('display','block');
	
        el.addEvent('mouseover', function() {
          el.setStyle('opacity','1');         
        });
	
        el.addEvent('mouseout', function() {
          el.setStyle('opacity','0.4');
        }); 
      }
  
      else if ( el ) {
        el.setStyle('display','none');
      }
        return true;
    }
	catch(e){
	ERRORS[1] = e;
	}
  }
});