var isiPad = navigator.userAgent.match(/iPad/i) != null;

// QTIP SETUP START
$.fn.qtip.styles.redevco = { // Last part is the name of the style
   width: 250,
   height: 140,
   background: config["PopupBackgroundColor"],
   color: config["PopupTextColor"],
   textAlign: 'left',
   border: {
      width: 1,
      radius: 0,
      color: config["PopupBorderColor"]
  },
  padding: 5, 
  tip: 'bottomLeft',
  name: 'dark' // Inherit the rest of the attributes from the preset dark style
}

// DEFAULT define corners and opposites arrays 
var corners = 'leftMiddle';
var opposites = 'rightMiddle';
var posx = 0;
var posy = 0;
//QTIP SETUP END

var isIE6 = false;
var posMapholder;

// @SAS: zoom circle now always needs to be in square, so width & height should be the same.
function mgZoomMap() {
	this.numDivs = 10;
	this.divPos = new Array();

	this.magRadius = 100;
	this.magHalfRad = 50;
	this.magCenterX = 100;
	this.magCenterY = 100;
	this.magContainerWidth  = 200;
	this.magContainerHeight = 200;

	this.mapWidth = 1;
	this.mapHeight = 1;
	this.zoomMapWidth = 2;
	this.zoomMapHeight = 2;

	this.zoomFactorX = 1.0;
	this.zoomFactorY = 1.0;

	this.zoomPosX = 0.0;
	this.zoomPosY = 0.0;
}

mgZoomMap.prototype.create = function (elem, numDivs, radius, mapWidth, mapHeight, zoomMapWidth, zoomMapHeight) {
	if (typeof(elem) == "undefined") {
		alert("mgZoomMap::create() - error: parameter elem is undefined");
	}

//	alert(radius);
	var rad = parseInt(radius);

	this.numDivs = numDivs;
	this.magRadius = rad;
	this.magHalfRad = rad / 2;

	this.mapWidth = mapWidth;
	this.mapHeight = mapHeight;
	this.zoomMapWidth = zoomMapWidth;
	this.zoomMapHeight = zoomMapHeight;

	this.magCenterX = rad;
	this.magCenterY = rad;
	this.magContainerWidth  = rad * 2;
	this.magContainerHeight = rad * 2;

	this.zoomFactorX = ((1.0 / mapWidth) * zoomMapWidth);
	this.zoomFactorY = ((1.0 / mapHeight) * zoomMapHeight);

	this.divPos = new Array();

	var x1,y2,x2,y2, w, h;
	var cnt=0;
	if (this.numDivs == 1) {
		x1 = 0;
		y1 = 0;
		w = this.magContainerWidth;
		h = this.magContainerHeight;
		elem.append('<div id="circrect_'+ cnt +'" class="zoommap_magrect" style="left:'+ x1 +'px;top:'+ y1 +'px;width:'+ w +'px;height:'+ h +'px;"></div>');
		this.divPos[cnt] = { x: x1, y: y1 };

	} else {
		var i;
		var r = this.magRadius;
		var step = Math.round(this.magContainerHeight / (this.numDivs+1));
//		var hstep = Math.floor(step/2);
		var hstep = Math.round(step/2);
//		var upperhalf = true;
		var upperhalf = false;

		for(i=-r+(hstep); i<=r-hstep; i+=step) {
//			b = Math.floor(Math.sqrt((r*r) - (i*i)));
			b = Math.round(Math.sqrt((r*r) - (i*i)));

			x1 = r - b;
			x2 = r + b;
			w = x2-x1;
			// We dont do anything on y=0
			if (i < 0) {
				y1 = r + (i * 1);
				y2 = y1 + step;
				h = this.magContainerHeight;

				elem.append('<div id="circrect_'+ cnt +'" class="zoommap_magrect" style="left:'+ x1 +'px;top:'+ y1 +'px;width:'+ w +'px;height:'+ step +'px;"></div>');
				this.divPos[cnt++] = { x: x1, y: y1, xx: x2, yy: y2 };
			} else if(i > 0) {
				if (upperhalf) {
					upperhalf = false;
				} else {
					y1 = r + (i*1) - step;
					y2 = y1 + step;
					elem.append('<div id="circrect_'+ cnt +'" class="zoommap_magrect" style="left:'+ x1 +'px;top:'+ y1 +'px;width:'+ w +'px;height:'+ step +'px;"></div>');
					this.divPos[cnt++] = { x: x1, y: y1, xx: x2, yy: y2 };
				}
			}
		}
	}
//	alert("created [-y,+y]: " + this.divPos[9].y +" - "+ this.divPos[9].yy);
//	alert("created [-y,+y]: " + this.divPos[10].y +" - "+ this.divPos[10].yy);
}

// @SAS: for now the posX and posY should be relative to the mask_circle_holder
mgZoomMap.prototype.rethinkPos = function (posX, posY) {
	// Set the div for the magnifying circle to our mouse position.
	$(".mask_circle_holder").css({
		left: posX - this.magCenterX,
		top: posY - this.magCenterY
	});

	var i, el, pos;
	for (i=0; i<this.divPos.length; i++) {
		pos = this.divPos[i];

		el = $("#circrect_" + i);
		if (typeof(el) != "undefined") {
			// Map position to our zoomed map
			sx = (this.magHalfRad - posX) * this.zoomFactorX - pos.x;
			sy = (this.magHalfRad - posY) * this.zoomFactorY - pos.y;
//			this.zoomPosX = sx;
//			this.zoomPosY = sy;
			this.zoomPosX = posX * this.zoomFactorX;
			this.zoomPosY = posY * this.zoomFactorY;
//			this.zoomPosX = (posX - this.magHalfRad) * this.zoomFactorX;
//			this.zoomPosY = (posY - this.magHalfRad) * this.zoomFactorY;
			el.css( {'background-position': + sx + 'px ' + sy + 'px'} );
//			el.css( {'border': '1px solid red'} );
		} else {
			alert("element ["+ str +"] typeof() = undefined!" );
			break;
		}
	}
}

var zoomMap = null;

var sensorEnable = true; 
$(document).ready(function() {

// Load the top and left cordination before posMapholder is set
$(".map_holder").css('margin-top', config["MapTop"]+'px');
$(".map_holder").css('left', config["MapLeft"]+'px');

if (!isiPad) {
	zoomMap = new mgZoomMap();

	if ( $.browser.msie ) {	//&& ($.browser.version && $.browser.version == "6.0") ) {
		isIE6 = true;
	}
//		isIE6 = true;

	if ( isIE6 ) {
//		zoomMap.create($(".mask_circle_holder"), 19, 80, 300, 300, 600, 600);
		zoomMap.create($(".mask_circle_holder"), 19, config["MaskRadius"]-3, config["ImageWidth"], config["ImageHeight"], config["ZoominImageWidth"], config["ZoominImageHeight"]);
	} else {
//		zoomMap.create($(".mask_circle_holder"), 1, 80, 300, 300, 600, 600);
		zoomMap.create($(".mask_circle_holder"), 1,  config["MaskRadius"], config["ImageWidth"], config["ImageHeight"], config["ZoominImageWidth"], config["ZoominImageHeight"]);
		$(".zoommap_magrect").addClass("mask_circle");
	}
	$(".mask_circle_holder").blur();

	$(".sensor").mousemove(function(e) {
      // Get some position info for our map, we need it to calc the relative position later
	  posMapholder = $(".map_holder").offset();
	  if (sensorEnable) {					
		// Get the relative mouse position, within the mapholder div
		var relX = e.pageX - posMapholder.left;
		var relY = e.pageY - posMapholder.top;

		zoomMap.rethinkPos(relX, relY);

		zmX = zoomMap.zoomPosX;
		zmY = zoomMap.zoomPosY;
		$.each(mapinfo, function(key, value) {
			xp = (parseInt(value[5]) + 15) + relX - zmX;
			yp = (parseInt(value[6]) + 15) + relY - zmY;
			$("#circle_"+key).css({"left": xp+"px", "top": yp + "px"});
		});

		// Is it okay to call this always?
		$(".mask_circle_holder").fadeIn(300);
	  }
	}).bind("mouseleave", function(e) {
		// Get the relative mouse position, within the mapholder div
		var relX = e.pageX - posMapholder.left;
		var relY = e.pageY - posMapholder.top;
		// Only fade out if we are outside the sensor area
		if( relX < 0 || relX > (zoomMap.mapWidth-2) || relY < 0 || relY > (zoomMap.mapHeight-2) ) {
			$(".mask_circle_holder").fadeOut(300);
		}
	});

	// If we move over the location dots, we want feedback and also keep scrolling the zoom
	$(".circle").mousemove(function(e) {
      // Get some position info for our map, we need it to calc the relative position later
	  posMapholder = $(".map_holder").offset();
		if (sensorEnable) {
		  // Get the relative mouse position, within the mapholder div
		  var relX = e.pageX - posMapholder.left;
		  var relY = e.pageY - posMapholder.top;
		  zoomMap.rethinkPos(relX, relY);
		}
	})
}

$(".mask_circle_holder").fadeOut(0);	

});

$(document).ready(function() {

  //GENERAL AIMAP SETUP
  var sensorWidth = config["ImageWidth"]; // normal image with
  var zoomImageWidth = sensorWidth * config["ZoominImageTimes"];
  var zoomImageContainerWidth = config["MaskRadius"];
  
  var sensorHeight = config["ImageHeight"];
  var zoomImageHeight = sensorHeight*config["ZoominImageTimes"];
  var zoomImageContainerHeight = config["MaskRadius"];
  
  //SETUP SENSOR WITH CIRCLES
  $.each(mapinfo, function(key, value) {
    $(".sensor").append('<a class="circle" id="circle_'+key+'" style="left: '+(value[5]-5)+'px; top: '+(value[6]-5)+'px;"></a>');
    $(".sensor").append('<a class="circle_small" id="circle_small_'+key+'" style="left: '+(value[8]-5)+'px; top: '+(value[9]-5)+'px;"></a>');
  });
  
  //SAVE ORIGINAL OFFSET FOR IPAD
  var oriTop = $('#circle_small_0').offset().top;
  var oriLeft = $('#circle_small_0').offset().left;


  //SETUP CSS MAP
  $(".map_holder").css('background-image', 'url("'+config["ImageUrl"]+'")');
  $(".map_holder").css('width', config["ImageWidth"]+'px');
  $(".map_holder").css('height', config["ImageHeight"]+'px');
  $(".sensor").css('width', config["ImageWidth"]+'px');
  $(".sensor").css('height', config["ImageHeight"]+'px');
  $(".zoommap_magrect").css('background-image', 'url("'+config["ZoominImageUrl"]+'")');

  $(".mask_circle_holder").css('width', (config["MaskRadius"]*2)+'px');
  $(".mask_circle_holder").css('height', (config["MaskRadius"]*2)+'px');
  $(".mask_circle").css('background-image', 'url("'+config["ZoominImageUrl"]+'")');
  $(".mask_circle").css('width', (config["MaskRadius"]*2)+'px');
  $(".mask_circle").css('height', (config["MaskRadius"]*2)+'px');
  $(".mask_circle").css('border-color', config["MaskBorderColor"]);
  $(".mask_circle").css('-o-border-radius', config["MaskRadius"]+'px'); /* Opera browser*/
  $(".mask_circle").css('-khtml-border-radius', config["MaskRadius"]+'px');/* K browser*/
  $(".mask_circle").css('-moz-border-radius', config["MaskRadius"]+'px'); /* FF */
  $(".mask_circle").css('-webkit-border-radius', config["MaskRadius"]+'px'); /* Saf3+, Chrome */
  $(".mask_circle").css('border-radius', config["MaskRadius"]+'px'); /* Opera 10.5, IE 9 */
  
  //QTIP - POPUP THING START
   $().mousemove(function(e){
    //You can now use window.mouseXPos and window.mouseYPos from anywhere.
      window.mouseXPos = e.pageX;
      window.mouseYPos = e.pageY;
   });

if (!isiPad) {
	$('.sensor .circle').click(function(e) {
		var circle_id = this.id;
		var spl_circle_id = circle_id.split('_');
		var only_circle_id = spl_circle_id[1];

		var ringSize = 72;
		$('.sensor .rollover_rings').remove();
		$(".sensor").append('<img src="'+config["RolloverImageUrl"]+'" class="rollover_rings" style="left: '+((($('#circle_small_'+only_circle_id).position().left)-(ringSize/2))+5)+'px; top: '+((($('#circle_small_'+only_circle_id).position().top)-(ringSize/2))+5)+'px;" />');

		// If counter reaches maximum, reset
		if ( (e.pageX - $('.map_holder').offset().left) / (sensorWidth) > 0.5) {
			corners = 'rightMiddle';
			opposites = 'leftMiddle';
			posx = 6;
		} else {
			corners = 'leftMiddle';
			opposites = 'rightMiddle';
			posx = -8;
		}
		$(".mask_circle_holder").fadeOut(300);

		// Destroy currrent tooltip if present
		if($(this).data("qtip")) $(this).qtip("destroy");

		sensorEnable = false; // hide the mask if circle is clicked
		$(this).html(opposites).qtip({// Set the links HTML to the current opposite corner
			content: { 
				text: '<div class="map_title">'+mapinfo[only_circle_id][0]+'</strong><br />'+mapinfo[only_circle_id][1]+'</div><div class="clear"></div><div class="map_content"><a href="'+mapinfo[only_circle_id][4]+'" title="read more" class="nodeco"><img src="'+mapinfo[only_circle_id][2]+'" title="'+mapinfo[only_circle_id][0]+'" /></a> <div class="map_description">'+mapinfo[only_circle_id][3]+'</div></div><div class="clear"></div><div><a href="'+mapinfo[only_circle_id][4]+'" title="read more">read more</a></div>'
			},
			position: { 
				target: $('#circle_small_'+only_circle_id),
				adjust: { 
					resize: true,
					y: -1, 
					x: posx 
				},
				corner: {
					tooltip: corners, // Use the corner...
					target: opposites // ...and opposite corner
				}
			},
			show: {
				when: false, // Don't specify a show event
				effect: {
					length: 200 },
					ready: true // Show the tooltip when ready
				},
			hide: { 
				when: 'unfocus',
				effect: { length: 200 },
				delay: 1000         
			},
			api: { 
				onShow: function(){ 
					sensorEnable = false; // hide the mask if circle is clicked
				},
				onHide: function(){ 
					sensorEnable = true; // show the mask if circle is hide
					$('.sensor .rollover_rings').remove();
				}
			},
			style: {
				tip: true, // Give it a speech bubble tip with automatic corner detection
				name: 'redevco' // Style it according to the preset 'cream' style
			}
		});
	});    
} else {

	$('#main').click(function(e) {
		$(this).qtip("destroy");
	});

	$('.sensor .circle_small').click(function(e) {

		var circle_id = this.id;
		var spl_circle_id = circle_id.split('_');
		var only_circle_id = spl_circle_id[2];

		var ringSize = 72;
		$('.sensor .rollover_rings').remove();
		$(".sensor").append('<img src="'+config["RolloverImageUrl"]+'" class="rollover_rings" style="left: '+((($('#circle_small_'+only_circle_id).position().left)-(ringSize/2))+5)+'px; top: '+((($('#circle_small_'+only_circle_id).position().top)-(ringSize/2))+5)+'px;" />');

		// If counter reaches maximum, reset
		if ( (e.pageX - $('.map_holder').offset().left) / (sensorWidth) > 0.5) {
			corners = 'rightMiddle';
			opposites = 'leftMiddle';
			posx = 13 - ($('#circle_small_0').offset().left - oriLeft);
			posy = - ($('#circle_small_0').offset().top - oriTop);
		} else {
			corners = 'leftMiddle';
			opposites = 'rightMiddle';
			posx = -3 - ($('#circle_small_0').offset().left - oriLeft);
			posy = - ($('#circle_small_0').offset().top - oriTop);
		}
		$(".mask_circle_holder").fadeOut(300);

		// Destroy currrent tooltip if present
		if($(this).data("qtip")) $(this).qtip("destroy");

		sensorEnable = false; // hide the mask if circle is clicked
		$(this).html(opposites).qtip({// Set the links HTML to the current opposite corner
			content: { 
				text: '<div class="map_title">'+mapinfo[only_circle_id][0]+'</strong><br />'+mapinfo[only_circle_id][1]+'</div><div class="clear"></div><div class="map_content"><a href="'+mapinfo[only_circle_id][4]+'" title="read more" class="nodeco"><img src="'+mapinfo[only_circle_id][2]+'" title="'+mapinfo[only_circle_id][0]+'" /></a> <div class="map_description">'+mapinfo[only_circle_id][3]+'</div></div><div class="clear"></div><div><a href="'+mapinfo[only_circle_id][4]+'" title="read more">read more</a></div>'
			},
			position: { 
				target: 'mouse',	
				adjust: { 
					mouse: true,
					scroll: false,
					resize: false,
					y: posy, 
					x: posx 
				},
				corner: {
					tooltip: corners, // Use the corner...
					target: opposites // ...and opposite corner
				}
			},
			show: {
				when: false, // Don't specify a show event
				effect: {
					length: 200 },
					ready: true // Show the tooltip when ready
				},
			hide: { 
				when: 'unfocus',
				effect: { length: 200 },
				delay: 1000         
			},
			api: { 
				onShow: function(){ 
					sensorEnable = false; // hide the mask if circle is clicked
				},
				onHide: function(){ 
					sensorEnable = true; // show the mask if circle is hide
					$('.sensor .rollover_rings').remove();
				}
			},
			style: {
				tip: true, // Give it a speech bubble tip with automatic corner detection
				name: 'redevco' // Style it according to the preset 'cream' style
			}
		});
	});
}  
	if ( $.browser.msie && $.browser.version == "6.0") {	//&& ($.browser.version && $.browser.version == "6.0") ) {
		DD_belatedPNG.fix('.map_holder');
	}
});
