//short cut for new ajax request - to avoid the length and repetitive 
function get(url){
   new Ajax.Request(url, {method: 'get',asynchronous:true, evalScripts:true,onLoading:function() {Element.show('loading');}, onComplete:function() {Element.hide('loading');}, onSuccess:function(transport){transport.responseText.evalScripts();}});
}

//like the above - short cut for ajax updater
function upd(url,target){
    new Ajax.Updater(target, url, {method: 'get',asynchronous:true, evalScripts:true, onLoading:function() {Element.show('loading');}, onComplete:function() {Element.hide('loading');}});
}

function u(url){
   new Ajax.Request(url,{method: 'get',evalScripts:true, onSuccess: function(transport){
		$('info').innerHTML = transport.responseText;
		transport.responseText.evalScripts();
		transport.responseText.extractScripts();
		Element.show('info');}
		});
}

//initiates the map 
function init_map(){
    map = new OpenLayers.Map($('map'),{projection:"EPSG:4326", numZoomLevels:15 });
    map.addLayer(new OpenLayers.Layer.GTileGrid("India",tile_url));
    map.setCenter(new OpenLayers.LonLat(lon, lat),zoom);
    markers =  new OpenLayers.Layer.Markers("posts");
    highlights = new OpenLayers.Layer.Markers("highlights");
    map.addLayer(markers);
    map.addLayer(highlights);
    map.addControl(new OpenLayers.Control.PanZoomBar());
    map.addControl( new OpenLayers.Control.MousePosition() );
    map.addControl( new OpenLayers.Control.MapunityText());
//    map.events.register("click",map, function(e){addData(e) ; Event.stop(e); });
    Element.hide("info"); 
}

function init(l,r,t,b,z) {
   init_map();
   var bounds = new OpenLayers.Bounds(l, b, r, t);
   map.zoomToExtent(bounds);
   map.zoomTo(z);
}


/*
 * recenters the map 
 */
function recenterMap(){
    //b = markers.getDataExtent();
    
    map.setCenter(bounds.getCenterLonLat());
    b2 = resizeExtent(bounds);
    zoom = map.getZoomForExtent(b2);
    if(zoom < 11){
    
    	//zoom = (minZoom > zoom) ? minZoom : zoom;
    }else{
    	zoom = (minZoom > zoom) ? zoom : minZoom;
    }
    map.zoomTo(zoom);
}


	function highlightMarker(lon,lat,desc,district,winning_party,id){
	        loc = new OpenLayers.LonLat(lon, lat);
		highlights.clearMarkers();
		marker = createMarker(lon,lat, desc,district, winning_party, id, true);
		highlights.addMarker(marker);
		map.setCenter(loc);
		if (district != 'BBMP-Bangalore') {
                map.zoomTo(9);
		} else { map.zoomTo(12); }
	        if( $('loading')) { Element.hide('loading');}
	}

	function showMarkers(constituencies) {
	        var results = eval(constituencies);
		results.each(function(result) { 
		    var loc = new OpenLayers.LonLat(result.lon, result.lat);
		    markers.addMarker(createMarker(result.lon, result.lat, result.name, result.district,result.winning_party, result.id, false)); 
		});
//		highlightMarker(loc,desc,z);
	}


    var offset = function(size) {return new OpenLayers.Pixel(-10,-26);};
    var BJPoffset = function(size) {return new OpenLayers.Pixel(-10,-24);};
    var INCoffset = function(size) {return new OpenLayers.Pixel(-10,-30);};
    var JDSoffset = function(size) {return new OpenLayers.Pixel(-10,-34);};
    var acicon = new OpenLayers.Icon("/images/ac.gif",new OpenLayers.Size(18,21),null,offset);
    var highlight_icon = new OpenLayers.Icon("/images/highlight.gif",new OpenLayers.Size(18,21),null,offset);
    var BJPicon = new OpenLayers.Icon("/images/BJP.png",new OpenLayers.Size(20,19),null,BJPoffset);
    var BJPhighlight_icon = new OpenLayers.Icon("/images/BJP_highlight.png",new OpenLayers.Size(20,19),null,BJPoffset);
    var INCicon = new OpenLayers.Icon("/images/INC.png",new OpenLayers.Size(25,25),null,INCoffset);
    var INChighlight_icon = new OpenLayers.Icon("/images/INC_highlight.png",new OpenLayers.Size(25,25),null,INCoffset);
    var JDSicon = new OpenLayers.Icon("/images/JDS.png",new OpenLayers.Size(20,30),null,JDSoffset);
    var JDShighlight_icon = new OpenLayers.Icon("/images/JDS_highlight.png",new OpenLayers.Size(20,30),null,JDSoffset);

/*
 *creates a default maker
 */
function createMarker(lon,lat,desc,district,winning_party, id, highlight){
    var loc = new OpenLayers.LonLat(lon, lat);
    var icon;
    switch(winning_party){
    	case "BJP" :
    		icon = highlight ? BJPhighlight_icon.clone() : BJPicon.clone();
		break;
	case "INC" :
    		icon = highlight ? INChighlight_icon.clone() : INCicon.clone();
		break;
	case "JD(S)" :
    		icon = highlight ? JDShighlight_icon.clone() : JDSicon.clone();
		break;
	default :
    		icon = highlight ? highlight_icon.clone() : acicon.clone();
		break;
    }

    var options = {"mouseOver":true};
    var marker= new OpenLayers.Marker.Label(loc,icon,desc,options);
    var zoom = 15;
    marker.events.register("click",marker, function(e){
         upd('/constituency/show_info/' + id, 'info');
	 Element.show('info');
    		highlightMarker(lon, lat,desc,district,winning_party, id);
    		highlightme(id);//,new OpenLayers.LonLat(loc.lon,loc.lat)); 
		Event.stop(e); 
    });
    //markers.addMarker(marker);
    return marker;
}

/*
 * highlights when the user clicks on the map
 */
function highlightme(id){
    $(id).className = "highlight";
//    $(id).scrollIntoView(true);
}

function closeInfo(){
	Element.hide("info");
}


/*
 * optimal resizing to fit the marker bounds
 */
function resizeExtent(bounds){
      bounds.left *= 0.99995;
      bounds.bottom *= 0.99995;
      bounds.right *= 1.00006;
      bounds.top *= 1.00006;
      return bounds;

}
// used with zoomToExtent for showing route result.
function createEnvelope(left,bottom,right,top)
{
  var l,b,r,t;
  if(left > right){
    l = right;
    r = left;
  }else{
    l = left;
    r = right;
  }
  if(top > bottom){
    t = top;
    b = bottom;
     
  }else{
    t= bottom;
    b = top;
  }
   
  return resizeExtent(new OpenLayers.Bounds(l,b,r,t));
}


/*
 * trim a string
 */
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
};


function showSource(){
	alert("The boundaries of the constituencies shown here are extracted from the constituency maps available at the election comission website as PDF documents. We would like to thank Sky Group for helping us in the data generation exercise");
}

function showMap() {
   bounds = map.getExtent();
   zoom = map.getZoom();
   url = "http://karnatakaelections.in/constituency/show_map?w=500&h=400&l=" + bounds.left + "&r=" + bounds.right + "&t=" + bounds.top + "&b=" + bounds.bottom + "&z=" + zoom;
   Element.update('info', '<span style="position:absolute;top:0px;right:0px;"><img src="/images/close.gif" onClick="closeInfo();" /></span><div style="height:220px;width:400px;padding:10px;margin:10px;">To embed the map in your webpage just copy the code snippet shown below. <br/> <br/> <textarea readonly cols=55>&lt;iframe alt="Maps by www.mapunity.org" scrolling=no frameborder=0 src="' + url + '"height="500" width="520" &gt;&lt;/IFRAME&gt;</textarea><br/><br/> By altering the values of the width and height parameters you can make map to suit the requirements of your webpage.</div>');
   Element.show('info');
}

var map;
var zoom = 9;
var lat = 13.78;
var lon= 75.95;
var markers ;
var highlights ;
var bounds ;
var marker ;
var color = "#fafdb6";
var ts = ".mapunity.org/ectiles";
var tp = "http://tiles";
var tile_url = [tp+'0'+ts,tp+'1'+ts,tp+'2'+ts,tp+'3'+ts,tp+'4'+ts,tp+'5'+ts];

