var headline_count;
var headline_interval;
var old_headline = 0;
var current_headline=0;
$(document).ready(function(){
  headline_count = $("div.headline").size();
  $("div.headline:eq("+current_headline+")").css('top','5px');
  
  headline_interval = setInterval(headline_rotate,4000); //time in milliseconds
  $('#scrollup').hover(function() {
    clearInterval(headline_interval);
  }, function() {
    headline_interval = setInterval(headline_rotate,4000); //time in milliseconds
    headline_rotate();
  });
});
function headline_rotate() {
  current_headline = (old_headline + 1) % headline_count; //remainder will always equal old_headline until it reaches headline_count - at which point it becomes zero. clock arithmetic
  $("div.headline:eq(" + old_headline + ")").animate({top: -205},"slow", function() {
    $(this).css('top','210px');
    });
  $("div.headline:eq(" + current_headline + ")").show().animate({top: 5},"slow");  
  old_headline = current_headline;
}
var GLOBAL_AREA_CLICK = '';
var CLICK_POS = new Array();
$(document).ready(function(){
	
	ImageMapSet();
	$('#resetmap').click(function(){
		ImageMapSet();
		$('#county').css("display","none");
		$('#service_options').css("display","none");
		$('#weightprice').css("display","none");
		$('#service_total').css("display","none");
		$('#weight').css("display","none");
		$('#closeout').css("display","none");
		$el('destination').selectedIndex = 0;
		$('#JTip').css("display","none");
		$('#mapallireland').attr("src","map/images/map-allireland.gif");
	});
	$('#closeapp').click(function(){
		Helper.closeOverlay();
	});
	$('#mapallireland').hover(
		function(){
		
		},
		function(){
			if(typeof GLOBAL_AREA_CLICK!='undefined' && GLOBAL_AREA_CLICK!=''){
				$('#JTip').css("display","block");
				var n = GLOBAL_AREA_CLICK.replace(/NIreland/gi,"Northern Ireland");
				n = n.replace(/AranIslands/gi,"Aran Islands");
				$('#JTip').html(n);
				$('#JTip').css("top",CLICK_POS['top']);
				$('#JTip').css("left",CLICK_POS['left']);
				
			} else {
				$('#JTip').css("display","none");
			}
		}
	);
});
function ImageMapSet(){
	var map = document.getElementsByTagName('area');
	for(var i=0;i<map.length;i++){
		map[i].onmouseover = showJTip;
		map[i].onmouseout = hideJTip;
		map[i].onclick = clickMap;
	}	
}
function findPos(obj) {
	var curleft = 0,curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	var scrOfX = 0, scrOfY = 0;
 		if( typeof( window.pageYOffset ) == 'number' ) {
   		  scrOfY = window.pageYOffset;
    	  scrOfX = window.pageXOffset;
  		} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    	//DOM compliant
    	  scrOfY = document.body.scrollTop;
          scrOfX = document.body.scrollLeft;
  		} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    	//IE6 standards compliant mode
    	  scrOfY = document.documentElement.scrollTop;
          scrOfX = document.documentElement.scrollLeft;
        }
	return [curleft,curtop];
}

function showJTip(e){
	$('#JTip').fadeIn(900);
	$('#JTip').css("display","inline");
	var pos = findPos($el(this.getAttribute("id")));
	var areaname = this.getAttribute("id").toLowerCase();
	areaname = areaname.replace(/[^a-z]/gi,"");
	$('#mapallireland').attr("src","map/images/map-"+areaname+".gif");
	//if(/MSIE/.test(navigator.userAgent)) {}
	
		var pos = findPos(document.getElementById('app'));
		$('#JTip').css("top",pos[1]+0);
		$('#JTip').css("left",pos[0]+80);
	var name = this.getAttribute("id")=='NIreland'?'Northern Ireland':this.getAttribute("id");
	if(this.getAttribute("id")=='AranIslands')
		name = 'Aran Islands';
	$('#JTip').html(name);	
}
function hideJTip(){
	if(typeof GLOBAL_AREA_CLICK!='undefined' && GLOBAL_AREA_CLICK!=''){
		var name = GLOBAL_AREA_CLICK.toLowerCase();
		$('#mapallireland').attr("src","map/images/map-"+name.replace(/[^a-z]/gi,"")+".gif");
	} else {
		$('#mapallireland').attr("src","map/images/map-allireland.gif");
		$('#JTip').css("display","none");
	}
	
}
function clickMap(e){
	GLOBAL_AREA = !this?arguments[0]:this.id;
	GLOBAL_AREA_CLICK = GLOBAL_AREA;
	$('#resetmap').css("visibility","visible");
	
		var pos = findPos(document.getElementById('app'));
		CLICK_POS['top'] = pos[1]+0;
		CLICK_POS['left'] = pos[0]+80;
	
}
function clickMapSelect(obj){
	if(/MSIE/.test(navigator.userAgent)) {
		GLOBAL_AREA = obj;
		obj = obj.toLowerCase();
		obj = obj.replace(/[^a-z]/gi,"");
		GLOBAL_AREA_CLICK = GLOBAL_AREA;
		var pos = findPos($el(obj));
		CLICK_POS['top'] = pos[1]+0;
		CLICK_POS['left'] = pos[0]+300;
	} else {
		GLOBAL_AREA = obj;
		obj = obj.toLowerCase();
		obj = obj.replace(/[^a-z]/gi,"");
		GLOBAL_AREA_CLICK = GLOBAL_AREA;
	}
}
function $el() {
	return document.getElementById(arguments[0]);
}
function bindEvent(el, sType, fn, capture) {
	if(window.attachEvent) {
		el.attachEvent("on" + sType, fn);
	} else if(window.addEventListener) {
		el.addEventListener(sType, fn, (capture));   
	}
}
function CurrencyFormatted(amount){
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
}

function init(){
	if(!$el('fmSearch')) return;
	bindEvent($el('m_mapallireland'),"click",getDestinations, false);
	bindEvent(document.forms['fmSearch'].elements['destination'], "change", getDestinations, false);
	bindEvent(document.forms['fmSearch'].elements['county'], "change", getCloseTime, false);
	bindEvent($el('getWeightPrice'), "click", getWeightPrice, false);
	bindEvent($el('kilo'), "keyup", function(){
		$el('weightprice').style.display = 'none';
		$el('service_options').style.display = 'none';
		$el('service_total').style.display = 'none';
		$el('wp_hidden').value = '';
	}, false);
	bindEvent($el('s1'), "click", getServicePrice, false);
	bindEvent($el('s2'), "click", getServicePrice, false);
	bindEvent($el('s3'), "click", getServicePrice, false);
	bindEvent($el('s4'), "click", getServicePrice, false);
	bindEvent($el('s5'), "click", getServicePrice, false);
	bindEvent($el('s6'), "click", getServicePrice, false);
	bindEvent($el('s7'), "click", getServicePrice, false);
	bindEvent($el('s8'), "click", getServicePrice, false);
	bindEvent($el('s9'), "click", getServicePrice, false);
	bindEvent($el('noweight'), "click", showServices, false);
}
function getDestinations(){
	if(this.event){
	var id = (this.event.srcElement.parentNode.id);
	} else {
	var id = this.id;
	}
	if(id=='m_mapallireland'){
		$el('county').style.display = 'none';
		var targ = GLOBAL_AREA;
		for(var k=0;k<$el('destination').options.length;k++){
			if($el('destination').options[k].value==GLOBAL_AREA){
				$el('destination').options.selectedIndex = k;
				break;
			}
		}
	} else {
		var targ = this.id==undefined?this.event.srcElement.value:this.value;
		clickMapSelect(targ);
		var name = targ.toLowerCase();
		areaname = name.replace(/[^a-z]/gi,"");
		$('#mapallireland').attr("src","map/images/map-"+areaname+".gif");
		$('#JTip').css("display","none");
		$('#JTip').fadeIn(900);
		var pos = findPos(document.getElementById('app'));
		CLICK_POS['top'] = pos[1]+0;
		CLICK_POS['left'] = pos[0]+80;
		$('#JTip').css("top",pos[1]+0);
		$('#JTip').css("left",pos[0]+80);
		var n = targ;
		if(targ=='NIreland')
			n = targ.replace(/NIreland/gi,'Northern Ireland');
		if(targ=='AranIslands')
			n = targ.replace(/AranIslands/gi,'Aran Islands');
		$('#JTip').html(n);	
	}
	YAHOO.util.Connect.asyncRequest("post","xhr/destinations.php",oCallback, "id="+targ);
}
function showServices(){
	$el('weightprice').style.display = 'none';
	for(var k=0;k<document.forms['fmSearch'].elements['service'].length;k++){
		document.forms['fmSearch'].elements['service'][k].checked = false;
	}
	$el('kilo').value = '';
	$el('wp_hidden').value = '';
	$el('service_total').innerHTML = '';
	$el('service_options').style.display = 'block';
}
function getCloseTime(){
	var targ = this.id==undefined?this.event.srcElement:this;
	YAHOO.util.Connect.asyncRequest("post","xhr/closeout.php",oCloseOut, "id="+targ.value);
}
function getServicePrice(){
	var targ = this.id==undefined?this.event.srcElement:this;
	postdata = "service="+targ.value+"&county="+$el('county').value;
	YAHOO.util.Connect.asyncRequest("post","xhr/serviceprice.php",oServicePrice, postdata);
}	
function getWeightPrice(){
	if(!$el('kilo').value.match(/^\d+$/) || parseInt($el('kilo').value)==0){
		alert("Please enter a valid weight using whole numbers only");
		return;
	}
	$el('weightprice').style.display = 'block';
	postdata = "weight="+$el('kilo').value+"&county="+$el('county').value;
	YAHOO.util.Connect.asyncRequest("post","xhr/weightprice.php",oWeightPrice, postdata);
}
oServicePrice = {
	success: function (oResponse) {
		$el('service_total').style.display = 'block';
		if(oResponse.responseText.match(/^[0-9.]+$/)){
			if($el('kilo').value==''){
				$el('service_total').innerHTML = "<p>The price for the selected Special Delivery service, excluding the consignment weight cost, is &pound;"+oResponse.responseText+"</p><p>This quote does not include our Fuel/Security/Insurance Surcharge. Our current surcharge amount is "+rate+"%</p>";
			} else {
				$el('service_total').innerHTML = "<p>The price for the selected service is £"+oResponse.responseText+"</p><p>The total, including Special Delivery service charge, is: &pound;"+CurrencyFormatted(parseFloat($el('wp_hidden').value)+parseFloat(oResponse.responseText))+"</p><p>This quote does not include our Fuel/Security/Insurance Surcharge. Our current surcharge amount is "+rate+"% ddd </p>";
			}
		} else {
			$el('service_total').innerHTML = "Please contact customer services for a quotation";
		};
	},
	failure: function (oResponse) {
		alert("The request failed");
	}
}
var oWeightPrice = {
	success: function (oResponse) {
		try {
			$el('weightprice').removeChild($el('weightprice').getElementsByTagName('p')[0]);
		} catch(e){
		
		}
		for(var k=0;k<document.forms['fmSearch'].elements['service'].length;k++){
			document.forms['fmSearch'].elements['service'][k].checked = false;
		}
		var p = document.createElement('p');
		p.style.display = 'inline';
		p.appendChild(document.createTextNode("£"));
		p.appendChild(document.createTextNode(oResponse.responseText));
		$el('wp_hidden').value = oResponse.responseText;
		$el('weightprice').appendChild(p);
		$el('weightprice').style.display = 'block';
		$el('service_options').style.display = 'block';
	},
	failure: function (oResponse) {
		alert("The request failed");
	},
	timeout:4000
};
var oCloseOut = {
	success: function (oResponse) {
		try {
			$el('closeout').removeChild($el('closeout').getElementsByTagName('span')[0]);
		} catch (e){
		
		}
		var span = document.createElement('SPAN');
		span.appendChild(document.createTextNode(oResponse.responseText));
		$el('closeout').style.display = 'block';
		$el('closeout').insertBefore(span,$el('closeout').getElementsByTagName('p')[0]);
		$el('weight').style.display = 'none';
		$el('weightprice').style.display = 'none';
		$el('service_options').style.display = 'none';
		$el('service_total').style.display = 'none';
	},
	failure: function (oResponse) {
		alert("The request failed");
	},
	timeout:4000
};
var oCallback = {
	success: function (oResponse) {
		//alert(oResponse.responseText);
		var fm = document.forms['fmSearch'];
		var jsonOptions = eval(oResponse.responseText);
		if(oResponse.responseText!=''){
			sel = $el('county');
			sel.disabled = false;
    		if(jsonOptions.length>0){
				sel.options[0] = new Option('Choose Town/Area ... ');
			}
			sel.options.length = 1;
			for(var i=0;i<jsonOptions.length;i++){
				sel.options[i+1] = new Option(jsonOptions[i].value, jsonOptions[i].key);
			}
			$el('county').style.display = 'block';
			$el('closeout').style.display = 'none';
			$el('weight').style.display = 'none';
			$el('weightprice').style.display = 'none';
			$el('service_options').style.display = 'none';
			$el('service_total').style.display = 'none';
			$el('kilo').value = '';
			$el('wp_hidden').value = '';
		} else {
			$el('county').options.length = 1;
			$el('county').disabled = true;
			$el('closeout').style.display = 'none';
			$el('weight').style.display = 'none';
			$el('weightprice').style.display = 'none';
			$el('service_options').style.display = 'none';
			$el('service_total').style.display = 'none';
		}
	},
	failure: function (oResponse) {
		alert("The request failed");
	},
	timeout:4000
};
function clearText(thefield){
if (thefield.defaultValue==thefield.value)
thefield.value = "";
} 
oServicePrice = {
	success: function (oResponse) {
		$el('service_total').style.display = 'block';
		if(oResponse.responseText.match(/^[0-9.]+$/)){
			if($el('kilo').value==''){
				$el('service_total').innerHTML = "<p>The price for the selected Special Delivery service, excluding the consignment weight cost, is &pound;"+oResponse.responseText+"</p><p>You can view our current surcharge rate on the News page.";
			} else {
				$el('service_total').innerHTML = "<p>The price for the selected service is £"+oResponse.responseText+"</p><p>The total, including Special Delivery service charge, is: &pound;"+CurrencyFormatted(parseFloat($el('wp_hidden').value)+parseFloat(oResponse.responseText))+"</p>";
			}
		} else {
			$el('service_total').innerHTML = "Please contact customer services for a quotation";
		};
	},
	failure: function (oResponse) {
		alert("The request failed");
	}
}
bindEvent(window, "load", init, false);