// 
//  ads.js
//  abm
//  
//  Created by Brian Putnam on 2010-08-03.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
// 


/**
*	Given a div to render to, and
*	JSON data to parse, create a
*	table in the wp-admin style
*/
function wp_admin_table(divId, json){
	var div = jQuery("#"+divId);
	var config = parseJsonObj(json);
	
	//----------------------------------
	//	Create the head and foot of the table
	//----------------------------------
	var ends = "<tr>";
	if(config.checkboxes){
		ends += "<th class='manage-column check-column'><input type='checkbox' /></th>";
	}
	for(var i = 0; i < config.columns.length; i++){
		if(config.columns[i].style){
			ends += "<th style='"+config.columns[i].style+"'>";
		}
		else{
			ends += "<th>";
		}
		ends += config.columns[i].name+"</th>";
	}
	ends += "</tr>";
	var head = "<thead>"+ends+"</thead>";
	var foot = "<tfoot>"+ends+"</tfoot>";
	
	//----------------------------------
	//	Create the body of the table
	//----------------------------------
	var body = "<tbody>";
	for(var row = 0; row < config.rows.length; row++){
		body += "<tr>";
		if(config.checkboxes){
			body += "<td><input type='checkbox' name='id[]' value='"+config.rows[row].id+"'/></td>";
		}
		for(var col = 0; col < config.rows[row].data.length; col++){
			body += "<td>"+config.rows[row].data[col]+"</td>";
		}
		body += "</tr>";
	}
	body += "</tbody>";
	
	var html = "<table class='widefat fixed' cellspacing='0'>"+head+foot+body+"</table>";
	div.html(html);
}

function parseJsonObj(json){
	json = json.replace(/^\/\/.*$/m, ""); //attempt to remove commented out lines
	json = json.replace(/0$/, ""); //for some reason, some of my return values end with an erroneous 0 character
	
	return eval("("+json+")");
}

function getSelected(tableName){
	return jQuery("#"+tableName+" input[type=checkbox]:checked");
}

function ads_onclick(id){
	ad_event(id, "click");
}

function ads_onview(id){
	ad_event(id, "view");
}

function ad_event(id, type){
	jQuery.ajax({
		//url: "/wp-admin/admin-ajax.php",
		//url: "/wp-content/plugins/advertising/ajax/ads/ads-ajax.php",
		url: "/ajax/ads/ads-ajax.php",
		data: {
			action: "record_ad_event",
			id: id,
			cache: false,
			type: type
		}
		 //,success: function(){
		 	//alert("click recorded!");
		 //}
	});
}
