var pageid,bug_group,myarrow_window;

//set up geoloaction groups
var americas = new Array("A1","A2","O1","AG","AI","AN","AQ","AR","AW","BB","BM","BO","BR","BS","BZ","CA","CL","CO","CR","CU","DM","DO","EC","FK","GD","GF","GL","GP","GS","GT","GY","HN","HT","JM","KN","KY","LC","MQ","MS","MX","NI","PA","PE","PM","PR","PY","SR","SV","TC","TT","UM","US","UY","VC","VE","VG","VI");
var asiapac = new Array("AF","AP","AS","AU","AZ","BD","BN","BT","CC","CK","CN","CX","CY","FJ","FM","GA","GE","GU","HK","HM","ID","IN","IO","JP","KG","KH","KI","KP","KR","LA","LK","MH","MM","MN","MO","MP","MV","MY","NC","NF","NP","NR","NU","NZ","PF","PG","PH","PK","PN","PW","SB","SG","TF","TH","TK","TL","TO","TV","TW","VN","VU","WF","WS");
var emea = new Array("AD","AE","AL","AM","AO","AT","AX","BA","BE","BF","BG","BH","BI","BJ","BV","BW","BY","CD","CF","CG","CH","CI","CM","CV","CZ","DE","DJ","DK","DZ","EE","EG","EH","ER","ES","ET","EU","FI","FO","FR","GB","GG","GH","GI","GM","GN","GQ","GR","GW","HR","HU","IE","IL","IM","IQ","IR","IS","IT","JE","JO","KE","KM","KW","KZ","LB","LI","LR","LS","LT","LU","LV","LY","MA","MC","MD","ME","MG","MK","ML","MR","MT","MU","MW","MZ","NA","NE","NG","NL","NO","OM","PL","PS","PT","QA","RE","RO","RS","RU","RW","SA","SC","SD","SE","SH","SI","SJ","SK","SL","SM","SN","SO","ST","SY","SZ","TD","TG","TJ","TM","TN","TR","TZ","UA","UG","UZ","VA","YE","YT","ZA","ZM","ZW");


$(document).ready(function(){
	
	pageid = $('body').attr('id');
	
	$('#submit_search').click(function(){
		$('#search').submit();
		return false;
	});
	
	$('#search').bind('submit', function(e){
		if($('#search_token').val() != ""){
			$(this).attr('action', 'http://components.arrow.com/part/search/' + fixSearchToken($(this).find('input:text', $(this)).val()));
			return true;		
		}else{
			return false;
		}		
	});		
	

	/* TEXT BOX HINTS */
	function hasPlaceholderSupport() {
		return ('placeholder' in document.createElement('input'));
	}
	
	/* TEXT BOX HINTS */
	$('input[type="text"][title]').focus(function() {
		if(hasPlaceholderSupport() && $(this).attr('placeholder')){return false;}
		if ($(this).val() === '' || $(this).val() === undefined || $(this).val() === $(this).attr('title')) {
			$(this).val('').removeClass('hinted');
		}
	}).blur(function() {
		if(hasPlaceholderSupport() && $(this).attr('placeholder')){return false;}
		if ($(this).val() === '') {
			$(this).val($(this).attr('title')).addClass('hinted');
		}
	}).filter(function() {
		if(hasPlaceholderSupport() && $(this).attr('placeholder')){return false;}
		if ($(this).val() === '' || $(this).val() === undefined || $(this).val() === $(this).attr('title')) {
			$(this).val($(this).attr('title')).addClass('hinted');
		}
	});
	/* END TEXT BOX HINTS */


	/*SETUP DROPDOWN MENUS*/
	$(".myarrowdropdown_head").hover(
		function() { 
			$('ul', this).css('display', 'block'); 
			$(this).addClass('myarrow_dd_hover');
		},
		function() { 
			$('ul', this).css('display', 'none'); 
			$(this).removeClass('myarrow_dd_hover');
		}
	);

	$(".regiondropdown_head").hover(
		function() {
			$('ul', this).css('display', 'block');
			$('.region_headlink').addClass('region_dd_hover');
		},
		function() {
			$('ul', this).css('display', 'none');
			$('.region_headlink').removeClass('region_dd_hover');
		}
	);
	/*END DROPDOWN MENUS*/
	
	//youramigo script
	ya_el('ya_fcats').className='ya_fcats1';



	if(pageid == "arrow_home"){
		
		randomize_images();
		
	}else if(pageid == "our_company"){
	
		$('#newslistings').html(newslinks);
		
	}else if(pageid == "arrow_components"){
	
		initGeolocation();	
		initContentSlider();
	
	}else if(pageid == "arrow_ecs"){
		
		initGeolocation();
		initContentSlider();
	
	}
	
	//HANDLE MYARROW LOGIN
	$('#comp_myarrow_login').live('click',function(){
		checkPopupClosed();
		var login_url = "https://components.arrow.com/cart/loginnac.jsp";
		myarrow_window = window.open(login_url,'popUp','height=625,width=825,left=150,top=150,resizable=yes,scrollbars=yes,toolbar=yes,menubar=yes,location=yes,directories=no,status=yes')
	
	});
	
});


//properly encode characters in search token
function fixSearchToken(input) {
	try{
		input = decodeURIComponent(input);
	}catch(err){}
	var fs = '';
	$.each(input.split('%'), function(i,o){
		if(i>0){
			if(i.toString().charAt(0)==" "){
				fs += "%";
			}else{
				fs += "% ";
			}
		}
		fs += o;
	});
	var s = '';
	$.each(fs.split('/'), function(i, o) {
		s += (i > 0 ? '/' : '') + encodeURIComponent(o);
	});
	return s;
}


//MYARROW LOGIN
function checkPopupClosed(){
	var t = setInterval(function(){
		if (myarrow_window.closed){
			window.location = "http://www.arrownac.com";
		}
	
	}, 1000)
}




//INITIALIZE CONTENT SLIDER
function initContentSlider(){
	featuredcontentslider.init({
		id: "slider1",  //id of main slider DIV
		contentsource: ["inline", ""],  //Valid values: ["inline", ""] or ["ajax", "path_to_file"]
		toc: "#increment",  //Valid values: "#increment", "markup", ["label1", "label2", etc]
		nextprev: ["<", ">"],  //labels for "prev" and "next" links. Set to "" to hide.
		revealtype: "click", //Behavior of pagination links to reveal the slides: "click" or "mouseover"
		enablefade: [true, 0.2],  //[true/false, fadedegree]
		autorotate: [true, 20000],  //[true/false, pausetime]
		onChange: function(previndex, curindex){  //event handler fired whenever script changes slide
			//previndex holds index of last slide viewed b4 current (1=1st slide, 2nd=2nd etc)
			//curindex holds index of currently shown slide (1=1st slide, 2nd=2nd etc)
		}
	});
}


//RANDOMIZE PAGE IMAGES
function randomize_images() {
	//create an array to store the images I want to randomly display
	var img_array = new Array();

	//specify the images with relative paths below
	img_array [1]="images/mainsection/home_photos/photo1.jpg";
	img_array [2]="images/mainsection/home_photos/photo2.jpg";

	/*
	if you want the images to link to something, then uncomment the lines below and add the links
	var imagelinks=new Array()
	imagelinks[1]="http://www.planetarrow.com/some/other/page1.html";
	imagelinks[2]="http://www.planetarrow.com/some/other/page2.html";
	imagelinks[3]="http://www.planetarrow.com/some/other/page3.html";
	*/

	// this line will randomly generate a number between 0 and the number of images you have in your img_array
	var i = Math.floor(Math.random()* img_array.length);
	if (i == 0) { i = 1; } //if the random number comes back zero assume image 1 
	
	// if you use image links comment the second document.write and uncomment the first
	//  document.write('<a href='+'"'+imagelinks[i]+'"'+'><img src="'+img_array[i]+'" border=0></a>');
	$('#photosection').append('<img src="'+img_array[i]+'" border=0></a>');
}



//STAT YOURAMIGO FUNCTIONS
function ya_el(x) {return document.getElementById(x)}

function ya_toggle_class(x, c1, c2) {
	x.className == c1 ? x.className=c2 : x.className=c1;
}

function ya_toggle_replace(x, s1, s2) {
	var text = x.innerHTML;
	text = text.match(s1) ? text.replace(s1, s2) : text.replace(s2, s1);
	x.innerHTML = text;
}

function ya_tog(x, a, c1, c2) {
   ya_toggle_class(ya_el(x), c1, c2);
   var a_el = ya_el(a);
   ya_toggle_replace(a_el, "[+]", "[-]");
}

//END YOURAMIGO SCRIPTS


//START GEOLOCATION FUNCTIONS

function initGeolocation(){
	var geoip_data,country,continent,ip,geoip_url,region;
	var country_cookie = document.cookie.match ( '(^|;) ?' + 'country' + '=([^;]*)(;|$)');
	
	bus_group = pageid = $('body').attr('id');
	
	if(country_cookie){
		country = unescape(country_cookie[2]);
		//setLinks(country);
		getRegion(bus_group,country);
	}else{
		geoip_url = $.ajax({
			url: 'http://www.arrow.com/geoip/getheaders.php',
			error: setLinks(bus_group,"americas"),
			success: function(data) {
				geoip_data = data.split('|');
				country = geoip_data[0];
				continent = geoip_data[1];
				ip = geoip_data[2];
				document.cookie = "country=" + country + "; domain=arrow.com;";
			},
			complete: function(){
				getRegion(bus_group,country);
			}
		});
	}
}

function getRegion(bus_group,country) {
	var am,ap,em,ndx;
	am = americas.length; ap = asiapac.length; em = emea.length; ndx = -1;
	region = '';
	// Has to happen at least once.  break out if ndx evals to number
	for (var i=0;i<am;i++) { if(americas[i] == country) { ndx = i; region='americas'; break; } }
	if (ndx == -1 || region == '') { for (var i=0;i<ap;i++) { if(asiapac[i] == country) { ndx = i; region='asiapac'		; break; } } }
	if (ndx == -1 || region == '') { for (var i=0;i<em;i++) { if(emea[i] == country) { ndx = i; region='emea'; break; } } }
	//alert(region);  //debug purposes
	setLinks(bus_group,region);
}

function setLinks(bus_group,geo){
	//changed to a switch so that each one is not evaluated makes for faster code and extensible for more granular breakdown if needed in future - 1/7/2011 anaruk
	if(bus_group == "arrow_components"){
		switch(geo) {
			case "emea":
				$('#services').attr('href', "http://www.arroweurope.com/services/");
				$('#products').attr('href', "http://www.arroweurope.com/");
				$('#manufacturers').attr('href', "http://www.arroweurope.com/linecard/");
				$('#markets').attr('href', "http://www.arroweurope.com/markets/");	
				break;
			case "asiapac":
				$('#services').attr('href', "http://components-asiapac.arrow.com/services/");
				$('#products').attr('href', "http://components-asiapac.arrow.com/cart/");
				$('#manufacturers').attr('href', "http://components-asiapac.arrow.com/manufacturers/");
				$('#markets').attr('href', "http://components-asiapac.arrow.com/reference_solutions/");
				break;
			case "americas": //fall through to default
			default: //Happens if not emea or asiapac.  If americas or if no geo returned.
				$('#services').attr('href', "http://www.arrownac.com/services-tools");
				$('#products').attr('href', "http://components.arrow.com/products/");
				$('#manufacturers').attr('href', "http://www.arrownac.com/manufacturers/");
				$('#markets').attr('href', "http://www.arrownac.com/solutions-applications/");
		}
	}else if(bus_group == "arrow_ecs"){
		switch(geo) {
			case "emea":
				$('#services').attr('href', "http://www.arrowecs.eu/services/");
				$('#products').attr('href', "http://www.arrowecs.eu/products/");
				$('#solutions').attr('href', "http://www.arrowecs.eu/solutions/");
				$('#about').attr('href', "http://www.arrowecs.eu/company/");	
				break;
			case "asiapac":
				$('#services').attr('href', "http://ecs.arrow.com/services/index.html");
				$('#products').attr('href', "http://ecs.arrow.com/suppliers/index.html");
				$('#solutions').attr('href', "http://ecs.arrow.com/partnerofferings/index.html");
				$('#about').attr('href', "http://ecs.arrow.com/aboutus/aboutus.html");
				break;
			case "americas": //fall through to default
			default: //Happens if not emea or asiapac.  If americas or if no geo returned.
				$('#services').attr('href', "http://ecs.arrow.com/services/index.html");
				$('#products').attr('href', "http://ecs.arrow.com/suppliers/index.html");
				$('#solutions').attr('href', "http://ecs.arrow.com/partnerofferings/index.html");
				$('#about').attr('href', "http://ecs.arrow.com/aboutus/aboutus.html");
		}
	}
}
//END GEOLOCATION FUNCTIONS
