var feedconfigcookiename='atn_feedconfig';

function cookieTest() {
	setCookie('atn_test','okay',1);
	if (getCookie('atn_test')==null) {
		$('cookiedisabledalert').style.display='block';
	}
}

function backupPref() {
	if (getCookie(feedconfigcookiename)!=null) {
		setCookie(feedconfigcookiename+"_backup",getCookie(feedconfigcookiename),1);
	}; 
}

function restorePref() {
	if (getCookie(feedconfigcookiename+"_backup")!=null) {
		setCookie(feedconfigcookiename,getCookie(feedconfigcookiename+"_backup"),365);
		} else {
		loadDefaultFeeds();
	}; 
}

function loadDefaultFeeds() {
    setCookie(feedconfigcookiename,'col1=tag_eur,tag_usd,tag_jpy|col2=tag_commodities,tag_fundamental,tag_tech_trading|col3=tag_econ_ind,tag_inst,tag_commentary',365);
}

function removefeed(feed_id,columnclass,feedclass,blockclass) {
	var columns = $A(document.getElementsByClassName(columnclass));
	columns.each(function(column) {
		var feeds = $A(column.getElementsByClassName(feedclass));
		feeds.each(function(feed) {
			if (feed.id==feed_id) {
				$(blockclass).appendChild($(feed));
				saveOrder(columnclass,feedclass);
			}
		});
	});	
}

function saveOrder(columnclass,feedclass) {
	var config=new Array();
	var columns = $A(document.getElementsByClassName(columnclass));
	columns.each(function(column) {	
		var blocks = $A(column.getElementsByClassName(feedclass));
		var s=new Array();
		blocks.each(function(block) {
			s.push(block.id);
		});
		config.push(column.id+'='+s);
	});

	setCookie(feedconfigcookiename,config.join('|'),365);				
	return false;
}

function clearColumns(columnclass,blockclass) {
	var columns = $A(document.getElementsByClassName(columnclass));
	columns.each(function(column) {	
            while($(column.id).hasChildNodes()){
                $(blockclass).appendChild($(column.id).firstChild);
            }
	});
}

function loadOrder(columnclass) {
	var columns = $A(document.getElementsByClassName(columnclass));
	columns.each(function(column) {	
			var feeds;
			if (getCookie(feedconfigcookiename)!=null) {
				getCookie(feedconfigcookiename).split("|").each(function(setting) {
					if (setting.split("=")[0] == column.id) {
						feeds=setting.split("=")[1];
					}
				});
			}
			
			if (feeds!=null) {
				feeds.split(",").each(function(feed) {
					if ($(feed)) { $(column.id).appendChild($(feed)) };
				})
			};
	});
}

function checkVisibleFeeds(blockclass,baseurl) { // only use in main
    if (getVisibleFeeds(blockclass)==0) {
        GB_myShowConfig('OANDA All Your News - Customize Your News Feeds',baseurl+'?op=config')
    }
}

function getVisibleFeeds(blockclass) {
	var feeds=0;
	feednames.each(function(feed) {
		if ($('feedbody_'+feed).parentNode.parentNode.id!=blockclass) {
			feeds++;
		}
	});
	return feeds;
}

function clearSettings() {
	setCookie(feedconfigcookiename,'',365);
}

function togglevoteimg(hash,dir) {
	if (dir=='up') {
		$("up_"+hash).title="You voted this up";
		$("dn_"+hash).style.visibility='hidden';
		$A($("up_"+hash).getElementsByClassName('vimg')).each(function(i) {i.src=supimg;i.alt="You voted this up";});
	} else if (dir=='dn') {
		$("dn_"+hash).title="You voted this down";
		$("up_"+hash).style.visibility='hidden';
		$A($("dn_"+hash).getElementsByClassName('vimg')).each(function(i) {i.src=sdownimg;i.alt="You voted this down";});
	}
	$("up_"+hash).onclick=null;
	$("up_"+hash).style.cursor='default';
	$("dn_"+hash).onclick=null;
	$("dn_"+hash).style.cursor='default';
}

function hasvoted(votehash) {
	var found=false;
	var upvar=getvotes('up',true);
	var dnvar=getvotes('dn',true)
	if (upvar!=null) { 
		upvar.each(function(day) {
			day.split('=')[1].split('|').each(function(entry) {
				if (entry.indexOf(votehash)>=0) { found=true; }
			});
		});
	}
	if (dnvar!=null) { 
		dnvar.each(function(day) {
			day.split('=')[1].split('|').each(function(entry) {
				if (entry.indexOf(votehash)>=0) { found=true; }
			});
		});
	}
	return found;
}

function highlightvotes(all) {
	if (getCookie('vlink')!=null) {
		getCookie('vlink').split("|").each(function(hash) {
			if (hash.length>0 && $("lhr_"+hash)) { $("lhr_"+hash).style.color='#868686';}
		});
	}
	var upvar=getvotes('up',true);
	var dnvar=getvotes('dn',true)
	if (upvar!=null) {
		upvar.each(function(day) {
			day.split('=')[1].split('|').each(function(hash) {
				if (hash.length>0 && $("up_"+hash)) { togglevoteimg(hash,'up');}
			});
		});
	}
	if (dnvar!=null) {
		dnvar.each(function(day) {
			day.split('=')[1].split('|').each(function(hash) {
				if (hash.length>0 && $("dn_"+hash)) { togglevoteimg(hash,'dn');}
			});
		});
	}
}

function getcookiename() {
	var d=new Date();
	var todayStr=(d.getYear()+1900)+"_"+d.getMonth()+"_"+d.getDate();
	var cookie='atn_v'+todayStr;
	return cookie;
}

// vote cookie structure: 
// atn_(dir)_yyyy_m_d = |upvoted_articleid:feedid|...&|dnvoted_articleid:feedid|...
// getvotes will return all 'dir'ection's votes stored in multi-cookies
function getvotes(dir,all) {
	var val;
	if (all) { val=getCookieRegex('atn_v[0-9]{4}_[0-9]{1,2}_[0-9]{1,2}') } else { val=getCookieRegex(getcookiename()); }
	if (val!=null) { 
		var result=new Array();
		if (dir=='up') {
			val.each(function(entry) {
				var prefix=entry.split('=')[0];
				var data=entry.split('=')[1];
				result.push(prefix+'='+data.split('&')[0]);
			});
		} else if (dir=='dn') {
			val.each(function(entry) {
				var prefix=entry.split('=')[0];
				var data=entry.split('=')[1];
				result.push(prefix+'='+data.split('&')[1]);
			});
		}
		return result;
	}
	return null;
}

// always adding to today's cookie
function addvote(dir,hash) {
	var val=getCookie(getcookiename());
	if (val!=null) { 
		if (dir=='up') {
			var x=val.split('&')[0].split('|');
			x.push(hash);
			setCookie(getcookiename(), x.join('|')+'&'+val.split('&')[1], 2); // two day expiry controls how many vote cookies are stored
		} else if (dir=='dn') {
			var x=val.split('&')[1].split('|');
			x.push(hash);
			setCookie(getcookiename(), val.split('&')[0]+'&'+x.join('|'), 2);
		}
	} else {
		if (dir=='up') {
			setCookie(getcookiename(), hash+'&', 7);
		} else if (dir=='dn') {
			setCookie(getcookiename(), '&'+hash, 7);
		}
	}
	return null;
}

function voteup(hash) {
	if (!hasvoted(hash)) {
		var cmdstr="op=voteup&hash="+hash;
		togglevoteimg(hash,'up');
		addvote('up',hash);
		sendAjaxRequest("/cgi/allnews.pl", statusResult, cmdstr);
	}
	return true;	
}

function votedown(hash) {
	if (!hasvoted(hash)) {
		var cmdstr="op=votedn&hash="+hash;
		togglevoteimg(hash,'dn');
		addvote('dn',hash);
		sendAjaxRequest("/cgi/allnews.pl", statusResult, cmdstr);
	}
	return true;	
}

function mark(hash) {
	setCookie('vlink',(getCookie('vlink')==null?"":getCookie('vlink'))+"|"+hash ,2);
	var cmdstr="op=mark&hash="+hash;
	sendAjaxRequest("/cgi/allnews.pl", statusResult, cmdstr);
	return true;	
}

function statusResult(req, success, url, odata){
	if (success) {
	        var status=req.responseText.split("&")[0].split("=")[1];
			window.status=status;
	} else {
			window.status="Error ["+req.status+"] loading "+url;	        
	}
}

// AJAX stuff
function getAjaxRequestType() {
  var xmlhttp;
  var activeXType;
  /*@cc_on
  @if (@_jscript_version >= 5)
    try {
      xmlhttp = new ActiveXObject(activeXType = "Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlhttp = new ActiveXObject(activeXType = "Microsoft.XMLHTTP");
      } catch (E) {
        xmlhttp = false;
      }
    }
  @else
  xmlhttp = false;
  @end @*/
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
    try {
      xmlhttp = new XMLHttpRequest();
    } catch (e) {
      xmlhttp = false;
    }
  }
  return activeXType;
}

var ieActiveXType = getAjaxRequestType();

function createAjaxRequest() {
  var xmlhttp;
  
  if (ieActiveXType) {
    xmlhttp = new ActiveXObject(ieActiveXType);
  } else {
    xmlhttp = new XMLHttpRequest();
  }
  return xmlhttp;
}

// if you do a GET, set data, mime to be null or don't pass them
// callback should have the following prototype
//
//      function aCallBack(req, success, url, originalData, opaqueId)
// url, originalData is to make it easy to properly identify to which request this response belongs to.
function sendAjaxRequest(url, callback, opt_data, opt_opaqueId, opt_mime) {

  // use a new private instance for every request
  var req = createAjaxRequest();
  var method = 'GET';
  if (opt_data) {
    method = 'POST';
    if (!opt_mime) {
      opt_mime = 'application/x-www-form-urlencoded';
    }
  }
  req.open(method, url, true);
  if (opt_data && opt_mime) {
    req.setRequestHeader('Content-Type', opt_mime);    // must be called after open
  }
  // stick the instance data into the scope of the function literal 
  req.onreadystatechange = function() {
    if (req.readyState == 4) {
      callback(req, req.status && req.status == 200, url, opt_data, opt_opaqueId);
      req.onreadystatechange = function () {}
    }
  };
  req.send(opt_data);
}

function setCookie(name,value,days) {
 if (days) {
   var date = new Date();
   date.setTime(date.getTime()+(days*24*60*60*1000));
   var expires = ";expires="+date.toGMTString();
 } else {
   expires = "";
 }
 document.cookie = name+"="+value+expires+";path=/";
}

// returns an array if regex matched, null if not
// array is ['var=value','var=value'] format
function getCookieRegex(regex) {
 var result=new Array();
 var re=new RegExp(regex);
 var needle = regex + "=";
 var cookieArray = document.cookie.split(';');
 for(var i=0;i <cookieArray.length;i++) {
   var pair = cookieArray[i];
   while (pair.charAt(0)==' ') {
     pair = pair.substring(1, pair.length);
   }
   var m=re.exec(pair);
   if (m!=null && m.index==0) {
     result.push(pair);
   }
 }
 if (result.length>0) { return result } else { return null };
}

function getCookie(name) {
 var needle = name + "=";
 var cookieArray = document.cookie.split(';');
 for(var i=0;i <cookieArray.length;i++) {
   var pair = cookieArray[i];
   while (pair.charAt(0)==' ') {
     pair = pair.substring(1, pair.length);
   }
   if (pair.indexOf(needle) == 0) {
     return pair.substring(needle.length, pair.length);
   }
 }
 return null;
}

function getDims(d) {
	if( typeof( window.innerWidth ) == 'number' ) {
	//Non-IE
		availW = window.innerWidth;
		availH = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		availW = document.documentElement.clientWidth;
		availH = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 quirks compatible
		availW = document.body.clientWidth;
		availH = document.body.clientHeight;
	}

	if (d=='x') return availW;
	if (d=='y') return availH;
}

function bookmark(url,title){
  if ((navigator.appName == "Microsoft Internet Explorer") && (parseInt(navigator.appVersion) >= 4)) {
  window.external.AddFavorite(url,title);
  } else if (navigator.appName == "Netscape") {
    window.sidebar.addPanel(title,url,"");
  } else {
    alert("Press CTRL-D (Netscape) or CTRL-T (Opera) to bookmark");
  }
}
