//_uacct = "UA-357779-4";
//urchinTracker();
	
var ALFIE = new Object();
ALFIE.Search = new Object();
ALFIE.Search.History = new Object();
ALFIE.Search.History.country = "us";
ALFIE.Search.Msg = new Object();
ALFIE.Search.Msg.default_str = "What are you looking for?";
ALFIE.Search.Msg.msg_finished = false;
ALFIE.Search.Msg.len = ALFIE.Search.Msg.default_str.length;
ALFIE.Search.Msg.c = 0;
	

function searchNow(q){
	var f = document.getElementById("searchform");
	var p = f.product.value;
	if(q){p=q;}
	if(p == ALFIE.Search.Msg.default_str || p == ""){
		alert("Type what you are looking for in Alfie's search box");
	}else{
		// us default
		var url_results = "/find/?q="+p;
		if(f.country[1].checked){
			url_results = "/uk/find/?q="+p;
			ALFIE.Search.History.country = "uk";
		}else if(f.country[2].checked){
			url_results = "/australia/find/?q="+p;
			ALFIE.Search.History.country = "au";
		}
		addToHistory(escape(p));
		document.location.href = url_results;
	}
}

		
function manageText(blurred){
	var f = document.getElementById("searchform").product;
	var m = ALFIE.Search.Msg;
	if(m.msg_finished){
		if(f.value == m.default_str){
			f.value = "";
			document.getElementById('product_field').style.color = "#017094";
		}else if(f.value == "" && blurred){
			f.value = m.default_str
			document.getElementById('product_field').style.color = "#cccccc";
		}else{
			document.getElementById('product_field').style.color = "#017094";
		}
	}
}


function writeMsg(first_time){
	var p = document.getElementById("searchform").product;
	var m = ALFIE.Search.Msg;
	if(first_time){
		p.value="";
	}
	if(m.c < m.len){
		p.value += m.default_str.charAt(m.c);
		m.c++;
		setTimeout("writeMsg();",20);
	}else{
		m.msg_finished = true;
		setTimeout('document.getElementById("searchform").product.focus();',1000);
	}
}

/****************** SEARCH PAGES  ****************/
function searchSite(id){
	// new windows?
	var new_win = false;
	// always new window for ebay
	if(document.searchform.new_window.checked || id == eBay){
		new_win = true;
	}
	var p = document.searchform.product.value;
	if(p == default_str){
		alert("Type what you are looking for in Alfie's search box");
	}else{
		// change tabs
		for(var i=0;i<websites.length;i++){
			document.getElementById('tab'+i).className = "";
		}
		document.getElementById('tab'+id).className = "selected";
		
		if(new_win){
			var tab = window.open(websites[id]+p);
			// also show holding page for ebay
			if(id == eBay){
				parent.site.location.href = "/ebay.html";
			}
		}else{
			parent.site.location.href = websites[id]+p;
		}
		if(urchinTracker){
			urchinTracker('/search_term/' + p);
		}
	}
}

function populateSearch(){
	thispage = parent.thispage;
	if(q != ""){
		document.searchform.product.value = q;
		document.getElementById('product_field').style.color = "#017094";
		searchSite(0);
	}else if(thispage.indexOf('?') == -1 || document.searchform.product.value == ""){
		writeMsg(1);
		//document.searchform.product.value = ALFIE.Search.Msg.default_str;
	}
}
/****************** END SEARCH PAGES  ****************/

function emailFriend(){
	urchinTracker('/email-a-friend/');
	document.location.href = "mailto:?subject=Auction Alfie: "+q+"&amp;body=Take a look at this "+q+":%0D%0A%0D%0A"+parent.document.location.href;
}

function bookmarkThis(site, url){
	var bookmark_link = "";
	var thispage = document.location.href;
	if(parent){
		thispage = parent.document.location.href;
	}
	if(url){
		thispage = url;
	}
	if(!q){
		var title = "Auction Alfie";
		var q = "";
	}else{
		var title = q + " search on Auction Alfie";
	}	
	switch (site){
		case "delicious":
			bookmark_link = "http://del.icio.us/post?url="+thispage+"&title="+title;
			break;
		case "facebook":
			bookmark_link = "http://www.facebook.com/sharer.php?u="+thispage;
			break;
		default:
			break;
	}
	if(bookmark_link != ""){
		urchinTracker('/track/bookmark/'+site+'/'+q);
		var bookmarkThis = window.open(bookmark_link);
	}
}

function setStatus(site){
	if(site){
		window.status = "http://"+site;
	}else{
		window.status = "";
	}
}

function highlightCode(el){
	document.getElementById(el).select();
}

function manageTabs(tabs_id, id){
	var tabs = document.getElementById(tabs_id).childNodes;
	var len = tabs.length;
	var len_looped = 0;
	// firefox fix
	for(var i=0;i<tabs.length;i++){
		var node = tabs[i].nodeName.toLowerCase();
		if(node == "li"){
			len_looped++;
		}
	}
	if(len_looped > 0){
		len = len_looped;
	}
	for(var i=1;i<=len;i++){
		document.getElementById(tabs_id+"_"+i).className = "";
		document.getElementById(tabs_id+"_div"+i).style.display = "none";
	}
	document.getElementById(tabs_id+"_"+id).className = "selected";
	document.getElementById(tabs_id+"_div"+id).style.display = "block";
}

function addOpenSearch(url){
	if ((typeof window.external == "object") && ((typeof window.external.AddSearchProvider == "unknown") || (typeof window.external.AddSearchProvider == "function"))) {
		window.external.AddSearchProvider(url);
	} else {
		alert("You will need to install a browser which supports OpenSearch for this plugin to work");
	}
}


// addToHistory("search", escape(q), q);

var today = new Date();
var expires = new Date(today.getTime() + (56 * 86400000));

function Set_Cookie(name,value,expires,path,domain,secure) {
	domain = ".auctionalfie.com";
	path = "/";
    document.cookie = name + "=" +escape(value) +
        ( (expires) ? ";expires=" + expires.toGMTString() : "") +
        ( (path) ? ";path=" + path : "") +
        ( (domain) ? ";domain=" + domain : "") +
        ( (secure) ? ";secure" : "");
}

function Get_Cookie(name) {
    var start = document.cookie.indexOf(name+"=");
    var len = start+name.length+1;
    if ((!start) && (name != document.cookie.substring(0,name.length))) return null;
    if (start == -1) return null;
    var end = document.cookie.indexOf(";",len);
    if (end == -1) end = document.cookie.length;
    return unescape(document.cookie.substring(len,end));
}


function Delete_Cookie(name,path,domain) {
    if (Get_Cookie(name)) document.cookie = name + "=" +
        ( (path) ? ";path=" + path : "") +
        ( (domain) ? ";domain=" + domain : "") +
        ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
/////// HISTORY ////////////////////


function getHistoryCookie(){
	var sh = ALFIE.Search.History;
	sh.cookie = Get_Cookie('searchhistory');
	
	if(sh.cookie != null && sh.cookie != ""){
		// if history cookie is used, eval JSON
		sh.data = eval('('+sh.cookie+')');
	}else{
		// create space for history
		sh.data = {};
		sh.data.searches = new Array();
		sh.data.country = ALFIE.Search.History.country;
	}
	/*
	sh.data = {};
	sh.data.searches = new Array();
	sh.data.searches[0] = "bike";
	sh.data.searches[1] = escape("bike 2");
	sh.data.searches[2] = "bike 3";*/
}

function addToHistory(q){
	getHistoryCookie();
	var sh = ALFIE.Search.History;
	var okToSave = true;
	var searches = sh.data.searches;
	sh.data.country = ALFIE.Search.History.country;
	// add latest search (if not duplicate search)
	if(searches && searches.length>=1){
		for(var i=0;i<searches.length;i++){
			if(searches[i] == q){
				okToSave = false;
			}
		}
	}
	if(okToSave){
		searches.unshift(q);
		//searches.unshift({"q":q,"title":title});
	}		
	if(searches.length > 5){
		searches.pop();
	}
	sh.cookie = sh.data.toJSONString();
	//alert(sh.cookie);
	Set_Cookie("searchhistory",sh.cookie,expires,'/');
}


function searchHistoryOutput(){
	getHistoryCookie();
	var sh = ALFIE.Search.History.data;
	if(sh.country == "uk"){
		document.getElementById("searchform").country[1].checked = true;
	}else if(sh.country == "au"){
		document.getElementById("searchform").country[2].checked = true;
	}
	var outputHTML = "";
	if(sh['searches'] != null && sh['searches'] != ""){
		// OUTPUT
		outputHTML += '<h2>Your last searches</h2><ul id="history" class="resources">';
		for(var i=0;i<sh.searches.length;i++){
			outputHTML += '<li><a href="javascript:searchNow(\''+sh.searches[i]+'\');">'+unescape(sh.searches[i])+'</a></li>';
		}
		outputHTML += '</ul>';
		outputHTML += '<p><a href="javascript:clearSearchHistory();" id="clearhistory">Clear latest searches on Auction Alfie?</a></p>';
	}
	if(outputHTML != ""){
		document.getElementById('history_holder').innerHTML = outputHTML;
	}
}


function clearSearchHistory(){
	Set_Cookie("searchhistory","",expires,'/');
	document.location.reload();
}


//////////////// END HISTORY //////////////		






//////////////////// JSON LIB ///////////////////

/*
json.js
2006-04-28

This file adds these methods to JavaScript:

object.toJSONString()

This method produces a JSON text from an object. The
object must not contain any cyclical references.

array.toJSONString()

This method produces a JSON text from an array. The
array must not contain any cyclical references.

string.parseJSON()

This method parses a JSON text to produce an object or
array. It will return false if there is an error.
*/
(function () {
var m = {
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
s = {
array: function (x) {
var a = ['['], b, f, i, l = x.length, v;
for (i = 0; i < l; i += 1) {
v = x[i];
f = s[typeof v];
if (f) {
v = f(v);
if (typeof v == 'string') {
if (b) {
a[a.length] = ',';
}
a[a.length] = v;
b = true;
}
}
}
a[a.length] = ']';
return a.join('');
},
'boolean': function (x) {
return String(x);
},
'null': function (x) {
return "null";
},
number: function (x) {
return isFinite(x) ? String(x) : 'null';
},
object: function (x) {
if (x) {
if (x instanceof Array) {
return s.array(x);
}
var a = ['{'], b, f, i, v;
for (i in x) {
v = x[i];
f = s[typeof v];
if (f) {
v = f(v);
if (typeof v == 'string') {
if (b) {
a[a.length] = ',';
}
a.push(s.string(i), ':', v);
b = true;
}
}
}
a[a.length] = '}';
return a.join('');
}
return 'null';
},
string: function (x) {
if (/["\\\x00-\x1f]/.test(x)) {
x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
var c = m[b];
if (c) {
return c;
}
c = b.charCodeAt();
return '\\u00' +
Math.floor(c / 16).toString(16) +
(c % 16).toString(16);
});
}
return '"' + x + '"';
}
};
Object.prototype.toJSONString = function () {
return s.object(this);
};
Array.prototype.toJSONString = function () {
return s.array(this);
};
})();

String.prototype.parseJSON = function () {
try {
return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
this.replace(/"(\\.|[^"\\])*"/g, ''))) &&
eval('(' + this + ')');
} catch (e) {
return false;
}
};
//////////////// END JSON LIB //////////////////

String.prototype.ucFirst = function () {
   var firstLetter = this.substr(0,1).toUpperCase()
   return this.substr(0,1).toUpperCase() + this.substr(1,this.length);
}