var $j = jQuery;
var dnaList = [];

//Initialization function
function wordjaxInit(){
	var l = dnaListRaw.length;
	for(var i = 0; i<l; i++){
		dnaList[i] = new RegExp(dnaListRaw[i]);
	}
	
	//Handle links
	$j("a").filter(wordjaxFilter).each(linkAttach);
	
	//Handle dropdown archive
	$j("select[onchange='document.location.href=this.options[this.selectedIndex].value;']").attr("onchange","").unbind("change.wordjax").bind("change.wordjax", function(){ wordjax(this.value);});
	
	//Handle forms
	$j('form[action = "' + siteURL + '"]').ajaxForm({
		url: adminURL+"/wp-content/plugins/wordjax/wordjax_request.php/",
		cache: false,
		success: wordjaxSuccess
	});
}

//Function that attaches the click handler to links
function linkAttach(){
	var obj = $j(this);
	var href = obj.attr("href");
	
	obj.unbind("click.wordjax");
	obj.bind("click.wordjax", function(){
		//$j("#" + contentId).html("");
		wordjax(href);
		return false;
	});
}

//Filter function to check which links should be hooked on to
function wordjaxFilter(idx){
	var currURL = location.href;
	var currURLNoHash = currURL;
	
	var idx = currURL.indexOf("#");
	if(idx >= 0) currURLNoHash = currURL.substring(0, idx);
	
	var url = $j(this).attr("href");
	
	//Check if it is an internal link
	if(url){
		//SPECIAL: Redefine href for paged pages
		var path = "/blog/wp-content/plugins/wordjax/wordjax_request.php";
		if(url.indexOf(path) >= 0){
			url = url.replace(path, "");
			url = url.substring(0, url.indexOf("?"));
			$j(this).attr("href", url);
		}
		
		//Exclude feeds
		if(url.match(/\/feed\/?$/)) return false;
		
		//Exclude Javascript
		if(url.match(/^javascript:/)) return false;
	
		//Exclude external links & anchors on the same page & admin pages
		if(url.indexOf(siteURL) == -1){
			return false; //external link
		}else{
			//Exclude admin pages
			if(url.indexOf(adminURL) >= 0) return false;
			
			//Exclude anchors on same page - TODO: Current page URL is not updated
			if ((hashIdx = url.indexOf("#")) != -1){
				//Anchor on same page (Relative path)
				if(hashIdx == 0) return false;
				
				//Anchor on same page (Absolute path)
				var urlNoHash = url.substring(0, hashIdx);
				if(currURL == urlNoHash) return false;
			}
		}
		
		//Exclude ignore list
		var l = dnaList.length;
		for(var i = 0; i<l; i++) if(url.match(dnaList[i])) return false;
	}else{
		//No href attribute
		return false;
	}
	
	return true;
}

//Function that sends the AJAX request
function wordjax(url){
	var suffix = url.substring(siteURL.length);
	if (suffix == "") suffix = "/";
	url = adminURL+"/wp-content/plugins/wordjax/wordjax_request.php"+suffix;
	
	$j.ajax({
		url: url,
		cache: false,
		success: wordjaxSuccess
	});
}

//Handler for AJAX request success
function wordjaxSuccess(html){
	var newContent = $j("#" + contentId, html);
	
	$j("#" + contentId).html(newContent.html()+add);
	$j("#" + contentId + " a").filter(wordjaxFilter).each(linkAttach);
}

$j(document).ready(wordjaxInit);