/* this file is a part of Check4Change
 *
 * Copyright 2010 Ronen Zilberman
 * See license.txt for details.
 */

//---------------------   c4cMenu -----------------------------
// Maybe I need to rewrite the menu code. Hiding irrelavant features.

//var c4cMenu_TIMES_ = [[5,'seconds'],[30,'seconds'],[1,'minutes'],[15,'minutes'],[1,'hours']];
var c4cMenu_TIMES = [];
var c4cMenu_TIMES_COUNT = 5;


var c4cMenu_MENUINDEX_ON_WHEN_RUNNING = new Array();
var c4cMenu_MENUINDEX_TIMES = new Array();
var c4cMenu_MENUINDEX_CUSTOM;
var c4cMenu_MENUINDEX_STOP;
var c4cMenu_MENUS = new Array(); // currently [0,1]

// 0 - content area context menu.
// 1 - tab context menu.
var c4cMenu_menuItems = new Array();
var c4cMenu_tabReference; // tab referenced by current menu action.



function c4cMenu_initContextMenus() {

	// create menuitems
  	menu = new Array(); // Normal context menu
  	var pos=0;
	var cur;
	var menu;

  	cur = document.createElement("menuitem");
  	cur.setAttribute("label", "Stop monitoring CUSTOM");
  	cur.setAttribute("oncommand", "c4cMenu_stop();");
  	c4cMenu_MENUINDEX_ON_WHEN_RUNNING[c4cMenu_MENUINDEX_ON_WHEN_RUNNING.length] = pos;
	c4cMenu_MENUINDEX_STOP = pos;
  	menu[pos++] = cur;

  	cur = document.createElement("menuitem");
  	cur.setAttribute("label", "Mark monitored text");
  	cur.setAttribute("oncommand", "c4cMenu_restoreSelection();");
  	c4cMenu_MENUINDEX_ON_WHEN_RUNNING[c4cMenu_MENUINDEX_ON_WHEN_RUNNING.length] = pos;
  	menu[pos++] = cur;


  	cur = document.createElement("menuseparator");
  	menu[pos++] = cur;

	for (var i=0; i< c4cMenu_TIMES_COUNT; i++) {
	  	cur = document.createElement("menuitem");
//		cur.setAttribute("label", "Check every "+c4cUti_durationToString(c4cMenu_TIMES[i][0], c4cMenu_TIMES[i][1]));
		cur.setAttribute("type", "radio");
		cur.setAttribute("name", "c4c_timeoption_radios");
// 		cur.setAttribute("oncommand", "c4cMenu_action("+c4cMenu_TIMES[i][0]+",'"+c4cMenu_TIMES[i][1]+"');");
		c4cMenu_MENUINDEX_TIMES[c4cMenu_MENUINDEX_TIMES.length] = pos;
  		menu[pos++] = cur;
  	}

  cur = document.createElement("menuitem");
  cur.setAttribute("label", "DYNAMIC");
  cur.setAttribute("type", "radio");
  cur.setAttribute("name", "c4c_timeoption_radios");
  //  cur.setAttribute("oncommand", "c4cMenu_actionCustomTime();");
  cur.setAttribute("oncommand", "c4cMenu_doAction(-1,-1);");

  c4cMenu_MENUINDEX_TIMES[c4cMenu_MENUINDEX_TIMES.length] = pos;
  c4cMenu_MENUINDEX_CUSTOM = pos;
  menu[pos++] = cur;

  cur = document.createElement("menuseparator");
  menu[pos++] = cur;

  cur = document.createElement("menuitem");
  cur.setAttribute("label", "Feedback...");
  cur.setAttribute("oncommand", "c4cSystem_goFeedback();");
  menu[pos++] = cur;

  cur = document.createElement("menuitem");
  if (c4cVIP_isVIP()) {
	cur.setAttribute("label", "VIP Profile...");
	cur.setAttribute("oncommand", "c4cSystem_goVIPProfile();");	
  }	else {
	cur.setAttribute("label", "Become a C4C VIP! :)");
	cur.setAttribute("oncommand", "c4cSystem_goBecomeVIP(4);");	
  }
	menu[pos++] = cur;
		
	cur = document.createElement("menuseparator");
	menu[pos++] = cur;
 
  
//-------------------------------  

  var tabContextMenu = gBrowser.tabContextMenu; // FF 4 
  if (!tabContextMenu)
      tabContextMenu = document.getAnonymousElementByAttribute(getBrowser(),"anonid","tabContextMenu"); // FF 3
  
  var regContextMenu = document.getElementById("contentAreaContextMenu");

  // create submenus
  var regMenu = document.createElement("menu");
  var mlabel = "Check4Change";
  if (c4cVIP_isVIP()) {
//		mlabel = mlabel+" (VIP)";
		regMenu.setAttribute("image", "chrome://c4c/content/vip.png");
  } else {
		regMenu.setAttribute("image", "chrome://c4c/content/c4c.ico");  
  }
  regMenu.setAttribute("class", "menu-iconic");	  
  regMenu.setAttribute("label", mlabel);
  var tabMenu = regMenu.cloneNode(false);
  regMenu.setAttribute("id","c4c_submenu");
  tabMenu.setAttribute("id","c4c_tab_submenu");

  // add them
  tabContextMenu.insertBefore(tabMenu, tabContextMenu.lastChild.previousSibling);
  tabContextMenu.insertBefore(document.createElement("menuseparator"), tabMenu);
//  regContextMenu.insertBefore(regMenu, document.getElementById("context-sep-stop"));
  regContextMenu.insertBefore(regMenu, document.getElementById("context-sep-selectall"));
  regContextMenu.insertBefore(document.createElement("menuseparator"), regMenu);

  // add menu popups
  var regMenuPopup = document.createElement("menupopup");
  var tabMenuPopup = regMenuPopup.cloneNode(false);
  regMenuPopup.setAttribute("id","c4c_submenu_popup");
  tabMenuPopup.setAttribute("id","c4c_tab_submenu_popup");

  // Compatability bug resolution with the MenuEditor Extension
/*regMenuPopup.addEventListener("popupshowing",c4cMenu_regularContextPopupShowing, false);
  tabMenuPopup.addEventListener("popupshowing",c4cMenu_tabContextPopupShowing, false);*/
  regMenuPopup.setAttribute("onpopupshowing","c4cMenu_regularContextPopupShowing();");
  tabMenuPopup.setAttribute("onpopupshowing","c4cMenu_tabContextPopupShowing();");

//  regMenuPopup.setAttribute("popupshowing");
  // add them
  tabMenu.insertBefore(tabMenuPopup, null);
  regMenu.insertBefore(regMenuPopup, null);

  // thread the menuitems and store them.
  c4cMenu_menuItems[0] = new Array();
  c4cMenu_menuItems[1] = new Array();


  // add menuitems to menus
  var b4r = null;
  var b4t = null;
  for (var x=menu.length-1;x>=0;x--) {
	  c4cMenu_menuItems[0][x] = menu[x]; //Store regular menuitems
	  c4cMenu_menuItems[1][x] = menu[x].cloneNode(false); // store tab menuitems
   	  c4cMenu_menuItems[0][x].setAttribute('id',"c4c_contentContextMenuItem"+x);
   	  c4cMenu_menuItems[1][x].setAttribute('id',"c4c_tabContextMenuItem"+x);

	  regMenuPopup.insertBefore(c4cMenu_menuItems[0][x],b4r);
	  tabMenuPopup.insertBefore(c4cMenu_menuItems[1][x],b4t);

	  b4r = c4cMenu_menuItems[0][x];
	  b4t = c4cMenu_menuItems[1][x];

  }

  c4cMenu_MENUS = [0,1];


}

// setup the action time commands
function c4cMenu_updateTimes() {
	//setup c4cMENU_TIMES
	var count=0;
	for (var i=0; i<c4cMenu_TIMES_COUNT; i++) {
		var val = c4cUti_getPrefInt("timeD"+i);
//		if (val==0) continue;

		c4cMenu_TIMES[count] = [val, c4cUti_getPrefString("timeU"+i)];
		count++;
	}

	for (var m in c4cMenu_MENUS) {
		for (var i=0; i< c4cMenu_TIMES.length; i++) {
	        var cur = c4cMenu_menuItems[m][c4cMenu_MENUINDEX_TIMES[i]];
			var on = c4cUti_getPref("timeE"+i);
			if (on) {
				cur.setAttribute("hidden", false);
			 	cur.setAttribute("label", "Check every "+c4cUti_durationToString(c4cMenu_TIMES[i][0], c4cMenu_TIMES[i][1]));
	 			cur.setAttribute("oncommand", "c4cMenu_doAction("+c4cMenu_TIMES[i][0]+",'"+c4cMenu_TIMES[i][1]+"');");
		    } else {
			  cur.setAttribute("hidden", true);
			}
		}
	}
}




function c4cMenu_regularContextPopupShowing(event) {
try{
	c4cMenu_tabReference = getBrowser().selectedTab; //HACK
	return c4cMenu_contextPopupShowing();

} catch (e) {c4cUti_assert(false,e); return true;}
}

function c4cMenu_tabContextPopupShowing(event) {
try{
	// HACK
  	var tab = getBrowser().mContextTab;
	if (tab.localName != "tab")
	    tab = getBrowser().mCurrentTab;

    c4cMenu_tabReference = tab;

	return c4cMenu_contextPopupShowing();

} catch (e) {c4cUti_assert(false,e); return true;}
}


function c4cMenu_contextPopupShowing() {
	// update the times in the menus.
    c4cMenu_updateTimes();

	// stop animation if running.
	c4cSytem_acknowledgeNotifications(c4cMenu_tabReference);

	for (var m in c4cMenu_MENUS) {

		var job = c4cSystem_findJobByTab(c4cMenu_tabReference);
	   	var off = (job == null);

		// set text for stop button
		if (off) {
			c4cMenu_menuItems[m][c4cMenu_MENUINDEX_STOP].setAttribute('label','Stop monitoring');
		} else {
			// calculate remaining time in most relavant time unit
			var remaining = job.timeToPulse();
			remaining = Math.round(remaining/1000);

			var str = c4cUti_timeInRelavantUnits(remaining);

			c4cMenu_menuItems[m][c4cMenu_MENUINDEX_STOP].setAttribute('label','Stop ('+str+' remaining)');
		}

		// take care of enabling/disabling menus depending on job being run
		for (var i in c4cMenu_MENUINDEX_ON_WHEN_RUNNING) {
			var ind = c4cMenu_MENUINDEX_ON_WHEN_RUNNING[i];
			c4cUti_enableMenuItem(c4cMenu_menuItems[m][ind], !off);
		}

		//reset custom
        c4cMenu_menuItems[m][c4cMenu_MENUINDEX_CUSTOM].setAttribute('label','Custom...');

        // reset selection
		// find first non-hidden menuitem and select&unselect it.
        for (var i=0;i<c4cMenu_TIMES_COUNT;i++) {
			var cur = c4cMenu_menuItems[m][c4cMenu_MENUINDEX_TIMES[i]];
			if (cur.getAttribute("hidden") != false) {
				cur.setAttribute('checked',true);
				cur.removeAttribute('checked');
			}
		}


        // if running, select correct time
        if (!off) {
			var ok = false;
			for (var i=0; i< c4cMenu_TIMES.length; i++) {
				// if this is the one, select it.
				if (job.params.duration == c4cMenu_TIMES[i][0] && job.params.units == c4cMenu_TIMES[i][1] && !job.params.advanced) {
					c4cMenu_menuItems[m][c4cMenu_MENUINDEX_TIMES[i]].setAttribute('checked',true);
					ok = true;
				}
			}
			// if not set, it's the custom
			if (!ok) {
		        c4cMenu_menuItems[m][c4cMenu_MENUINDEX_CUSTOM].setAttribute('label','Custom ('+c4cUti_durationToString(job.params.duration, job.params.units)+')...');
				c4cMenu_menuItems[m][c4cMenu_MENUINDEX_CUSTOM].setAttribute('checked',true);
			}
		}
	}


 	return true;
}

function c4cMenu_stop() {
	var job = c4cSystem_findJobByTab(c4cMenu_tabReference);
	if (job == null) return;
	
	job.stop();
}

function c4cMenu_assureSelection(tab) {
	// test if window has a selection
	if (!c4cUti_hasSelection(c4cUti_getWindowFromTab(tab))) {
		// if not, check if this is an update, I.E a running job. If so it's ok.
		var job = c4cSystem_findJobByTab(tab);
		if (job != null) return true;

		// otherwise notify
		var res = c4cUti_confirm(window, "Check4Change Usage Instructions", "Check4Change basic usage:\n\n1. Select the text to monitor with the mouse or keyboard.\n2. From the Check4Change menu, select the testing interval, or \"Custom...\" for advanced features.\n\n Would you like to see a tutorial?");
		if (res) {
		    c4cUti_addTab('http://www.check4change.com/tutorial?o=e&'+c4cStats_getQueryString(), true);			
		}
		return false;
	}
	return true;
}

function c4cMenu_assurePostData(tab) {
  var metaData = c4cUti_getTabMetaData(tab);
  if (metaData.postData != null) {
    return c4cUti_confirm(window, "Continue?", "This tab contains POST data. Press OK to resend this data every refresh.\n\nThis is usually the right thing to do, unless you have just performed an action you do not wish to repeat (such as an online purchase).");
  }
  return true;
}

function c4cMenu_doAction(time, unit) {
try{

  // this is to cause the context-menu to close
  window.setTimeout(c4cMenu_action, 0, time, unit);

} catch (e) {c4cUti_assert(false,e);}
}

function c4cMenu_action(time, unit) {
try{
	c4cUti_assert(c4cMenu_tabReference);

	var ok = c4cMenu_assureSelection(c4cMenu_tabReference);
	if (!ok) return;

	ok = c4cMenu_assurePostData(c4cMenu_tabReference);
	if (!ok) return;	


	// set params
	var params = c4cParams_getCurrentDefaults();
	
	// one of the fixed time jobs.
	if (time != -1) {
	  // create or update the job.
	  params.duration = time;
	  params.units = unit;
	} else { // custom time

	  var job = c4cSystem_findJobByTab(c4cMenu_tabReference);
	  if (job != null) params = c4cUti_cloneObject(job.params);

	  var diag_params = new Array();
	  diag_params['params'] = params;
	  var res = window.openDialog('chrome://c4c/content/AdvancedDialog.xul','','chrome,centerscreen,modal',diag_params);
	  params = diag_params['params'];
	  if (params.cancel) return;
	  
      params.advanced = true;
	}

	// run
	c4cSystem_makeJob(c4cMenu_tabReference, params);


} catch (e) {c4cUti_assert(false,e);}
}


function c4cMenu_restoreSelection() {
try{
	var job = c4cSystem_findJobByTab(c4cMenu_tabReference);
	if (job) job.restoreSelection();
} catch (e) {c4cUti_assert(false,e);}
}


//------------------------------------------------------------------------------

function c4cParams_getHardDefaults() {
	var params = {
		timeD0: 30,
		timeU0: "seconds",
		timeE0: true,
		timeD1: 5,
		timeU1: "minutes",
		timeE1: true,		
		timeD2: 15,
		timeU2: "minutes",
		timeE2: true,		
		timeD3: 1,
		timeU3: "hours",
		timeE3: true,		
		timeD4: 4,
		timeU4: "hours",
		timeE4: true,		
		
//		advanced: false,
//		duration : null,
//		units : null,
		delayDuration : 3,
		doRandom : false,
		randomPercentage: 0,
		doContinue : false,
		doStopWhenViewing : false,
		dontReload : false,
		notifyAnim : true,
		notifyTaskBar : true,
		notifyPopup : true,
		notifySound:true,
		notifyFocus:false,
		notifyLog:false,
		notifyEmail:false,
		soundFile:c4cSystem_defaultSoundName,
		soundVolume: 50,
		logDir: c4cUti_appendFileToDir(c4cUti_getHomeDir(), "check4change-logs"),
		notifySoundContinuous:false,
		doAllowNav:false,
		doCountDown:true,
		doReselect:true,
		doDebug: false
	};
	return params;
	
}


function c4cParams_setUpSystemDefaults() {
  var params = c4cParams_getHardDefaults();
  
  for (var p in params) {
	if (!c4cUti_isPref(p)) {
		c4cUti_setPref(p, params[p]);
	}
  }
}

function c4cParams_getCurrentDefaults() {
	var params = c4cParams_getHardDefaults();
	
	for (var p in params) {
		var v = c4cUti_getPref(p);
		if (v !== null) {
			params[p] = v;
		}
	}

//  params.doAbsPos = false;
  return params;

}

function c4cParams_setupDialog(params) {
	if (params == null) params = new Array();
	var li = document.getElementsByClassName("option");
	for (var i=0;i<li.length;i++) {
		var e = li[i];
		
		var val;
		if (params[e.id] !== undefined) {
			val = params[e.id];
		} else  {
		    val = c4cUti_getPref(e.id);
		}
		if (val === null) continue;
		
		switch (e.nodeName) {
			case "checkbox": 
				e.checked = val;
				break;
			case "menulist":
				c4cUti_setMenuListValue(e, val);
				break;
			case "scale":				
			case "textbox":
				e.value = val;
				break;
				
			default: c4cUti_assert("Unsupported Nodename get "+e.nodeName);
		}
	}	
}

function c4cParams_getFromDialog(curParams) {
	if (curParams === null) curParams = new Array();
	var li = document.getElementsByClassName("option");
		
	for (var i=0;i<li.length;i++) {
		var e = li[i];
		var isInt = false;
		var val=null;
		switch (e.nodeName) {
			case "checkbox": 
				val = e.checked;
				break;
			case "menulist":
				val = c4cUti_getMenuListValue(e);
				break;
			case "scale":
				isInt = true;
			case "textbox":
				if (c4cUti_hasClass(e, "number")) isInt = true;
				if (isInt)
					  val = parseInt(e.value);
				else  val = e.value;
				break;
				
			default: c4cUti_assert("Unsupported Nodename set "+e.nodeName);
		}
		curParams[e.id] = val;
	}

	return curParams;
}

function c4cParams_saveFromDialog() {
	var params = c4cParams_getFromDialog(null);
	for (var p in params) {
		c4cUti_setPref(p, params[p]);
	}
}

//-------------------------- stats
var c4cStats_PREFIX = "stats.";

// return the cookie params as GET params if there is a problem with the cookie setter.
function c4cStats_getQueryString() {
	if (!c4cUti_cookieBugFlag) return "";
	
	var s = "c4c="+c4cUti_getPrefString(c4cStats_PREFIX+"installDate");
	var vipid = c4cVIP_getID();
	if (vipid) {
		s = s+"&vipid="+vipid;
	}
	return s;
}

function c4cStats_init() {
	if (c4cUti_getPrefString(c4cStats_PREFIX+"installDate") == null) {
		c4cUti_setPrefString(c4cStats_PREFIX+"installDate",new Date().getTime());
	}
	
	c4cUti_setCookie("http://check4change.com", "c4c", c4cUti_getPrefString(c4cStats_PREFIX+"installDate"), ".check4change.com");
	var vipid = c4cVIP_getID();
	if (vipid) {
		c4cUti_setCookie("http://check4change.com", "vipid", vipid, ".check4change.com");
	}	
}

function c4cStats_totalMonitoringTime() {
  var total = 0;

  var counts = c4cUti_getAllPrefs(c4cStats_PREFIX+"timeCount.");
  for (i in counts) {
    // get the last part of the pref which is like 7seconds
    var str = counts[i].split('.');
    str = str[str.length-1];
    var duration = parseInt(str);
    var mul = 1;
    if (-1 != str.indexOf('minutes')) mul = 60;
    if (-1 != str.indexOf('hours')) mul = 3600;
    var count = c4cUti_getPrefInt(counts[i], true);

    total += duration*mul*count;

  }
  
  return total;
}

function c4cStats_totalJobCount() {
try {
  var total = 0;
  
  var counts = c4cUti_getAllPrefs(c4cStats_PREFIX+"timeCount.");
  for (i in counts) {
    var count = c4cUti_getPrefInt(counts[i], true);
    total += count;
  }
  return total;
} catch(e) {return 0;}  
}

function c4cStats_getRefreshCount() {
	return c4cUti_getPrefInt(c4cStats_PREFIX+"refreshCount");
}

function c4cStats_getChangeCount() {
	return c4cUti_getPrefInt(c4cStats_PREFIX+"changeCount");
}
function c4cStats_getInstallDate() {
	return c4cUti_getPrefString(c4cStats_PREFIX+"installDate");
}


function c4cStats_newJob(job) {
	var params = job.params;
	
	var name = c4cStats_PREFIX+"timeCount."+params.duration+params.units;
	c4cUti_incPrefInt(name);

	if(params.notifyAnim) c4cUti_incPrefInt(c4cStats_PREFIX+"notifyAnim");
	if(params.notifyTaskBar) c4cUti_incPrefInt(c4cStats_PREFIX+"notifyTaskBar");
	if(params.notifyPopup) c4cUti_incPrefInt(c4cStats_PREFIX+"notifyPopup");
	if(params.notifySound) c4cUti_incPrefInt(c4cStats_PREFIX+"notifySound");
	if(params.notifyFocus) c4cUti_incPrefInt(c4cStats_PREFIX+"notifyFocus");
	if(params.notifyLog) c4cUti_incPrefInt(c4cStats_PREFIX+"notifyLog");	
	if(params.notifyEmail) c4cUti_incPrefInt(c4cStats_PREFIX+"notifyEmail");	

	if(params.advanced) c4cUti_incPrefInt(c4cStats_PREFIX+"advanced");
	if(params.doRandom) c4cUti_incPrefInt(c4cStats_PREFIX+"doRandom");
	if(params.doContinue) c4cUti_incPrefInt(c4cStats_PREFIX+"doContinue");
	if(params.doStopWhenViewing) c4cUti_incPrefInt(c4cStats_PREFIX+"doStopWhenViewing");
	if(params.dontReload) c4cUti_incPrefInt(c4cStats_PREFIX+"dontReload");
//	if(params.doAllowNav) c4cUti_incPrefInt(c4cStats_PREFIX+"doAllowNav");
    if(params.doAbsPos) c4cUti_incPrefInt(c4cStats_PREFIX+"doAbsPos");
    if(params.notifySoundContinuous) c4cUti_incPrefInt(c4cStats_PREFIX+"notifySoundContinuous");
	
	c4cUti_incPrefInt(c4cStats_PREFIX+"location."+job.location);
	c4cUti_setPrefString(c4cStats_PREFIX+"lastJob",job.location);
	if (job.postData) c4cUti_incPrefInt(c4cStats_PREFIX+"POST");


}
function c4cStats_refresh() {
	c4cUti_incPrefInt(c4cStats_PREFIX+"refreshCount");
}

function c4cStats_change() {
	c4cUti_incPrefInt(c4cStats_PREFIX+"changeCount");
}

function c4cStats_cantContMsg() {
	c4cUti_incPrefInt(c4cStats_PREFIX+"cantContMsg");
}

function c4cStats_statStr() {
try {
	var obj = c4cUti_PrefsObj();
	obj["zz_OS"] = c4cUti_getOSString();
	obj["zz_FF_VER"] = c4cUti_getFireFoxVersion();
	obj["zz_C4C_VER"] = c4cUti_getExtensionVersion();
	obj["zzz_EXTENSIONS"] = c4cUti_getAllExtensionsVersion();
	obj["zzz_C4C_LOC"] = c4cUti_c4cXpiPath;
	
	var str = c4cUti_Base64.encode(JSON.stringify(obj));
	return str;
}	
catch (e) {return "";}	
}

function c4cStats_fbset(doc) {
try {
	var e = doc.getElementById("__c4cstats");
	if (e == null) return;

	e.value = c4cStats_statStr();
} catch (e) {}	
}