//=============================================================================
// File: compaign.js
// Common javascript code.
//
// Author: 
// carl.phillips@gmail.com
// odin.phillips@gmail.com
//=============================================================================	

/** Maximum number of campaign steps. */
var MAX_CAMPAIGN_STEPS = 7;

/** An array with all the step 'div' IDs. */
var g_cstep = new Array();
g_cstep[0] = "cstep_name";
g_cstep[1] = "cstep_country";
g_cstep[2] = "cstep_website";
g_cstep[3] = "cstep_keywords_cpc";
g_cstep[4] = "cstep_ad";
g_cstep[5] = "cstep_budgets_cpc";
g_cstep[6] = "cstep_fund";
g_cstep[7] = "cstep_login";

/** The current campaign step that is/will be visible to the user */
var g_campaign_step = 0;

function updateCampaignSteps()
{
	var format = document.getElementById('c_format_cpc').checked?'cpc':'cpm';
	g_cstep[3] = "cstep_keywords_" + format;
	g_cstep[5] = "cstep_budgets_" + format;
	if(format == 'cpm')
		$('tr.ad_text_step').hide();
		else $('tr.ad_text_step').show();
}

function updatePasswordStrength()
{		
	var password = document.getElementById('newpassword').value;
	var strength = 0;

	// easy_guesses: strings that should not be used in password
	var easy_guesses = new Array();
	easy_guesses.push('password'); // does this need to be localized?
	easy_guesses.push('invideous');

	var email_words = document.getElementById('youremail').value.match(/\w+/g); // contiguous words contained in email
	if (email_words)
		easy_guesses = easy_guesses.concat(email_words);

	var locase_matches = password.match(/[a-z_]/g); // lowercase and '_' matches
	var digit_matches = password.match(/[0-9]/g);   // numeric matches
	var upcase_matches = password.match(/[A-Z]/g);  // uppercase matches
	var special_matches = password.match(/\W/g);    // special matches (not in a-z, A-Z, 0-9, _)
	
	if (password.length>5) {
		// for less than 5, leave strength at 0 since password too short

		// 1 point for each character more than 5
		strength += password.length - 5;

		// 1 point for each upcase character mixed with lowercase
		if (locase_matches && upcase_matches)
			strength += upcase_matches.length;

		// 1 point for each numeric character mixed with lowercase
		if (locase_matches && digit_matches)
			strength += digit_matches.length;

		// 1 point for each special characters
		if (special_matches)
			strength += special_matches.length;

		// 2 bonus points if mix of letters, numbers and special
		if ((locase_matches || upcase_matches) && special_matches && digit_matches)
			strength += 2;
	}

	// Reset strength to 0 if any easy guess in password (easy guess should be more than 3 chars)
	for (var i=0; i < easy_guesses.length; i++)
	{			
		if (easy_guesses[i].length>3 && (password.indexOf(easy_guesses[i])!=-1)) {
			strength=0;
			break;
		}
	}

	var passwordStrength = document.getElementById('password_strength');
	var passwordStrengthText = document.getElementById('password_strength_text');
	if (password.length==0)
	{
		passwordStrength.className = 'password_empty';
		passwordStrengthText.innerHTML = 'None';
	}
	else if (strength<3)
	{			
		passwordStrength.className = 'password_weak';
		passwordStrengthText.innerHTML = 'Weak';
	}
	else if (strength<7)
	{
		passwordStrength.className = 'password_fair';
		passwordStrengthText.innerHTML = 'Fair';
	}
	else if (strength<10)
	{
		passwordStrength.className = 'password_good';
		passwordStrengthText.innerHTML = 'Good';
	}
	else
	{
		passwordStrength.className = 'password_strong';			
		passwordStrengthText.innerHTML = 'Strong';
	}
}

function onCampaignSubmit()
{		
	var loggedIn =  document.getElementById('c_login');
	
	if(checkCampaignValid())
	{
		document.campaign_form.submit();
		return true;
	}
	return false;
}	

/**
* Checks all the campaign fields for errors.
*
* @return	Returns true is all the fields are correct, othewise false.
* @author	odin.phillips@gmail.com
*/
function checkCampaignValid()
{
	$('#errors').html('');
	var campaign_format = document.getElementById('c_format_cpc').checked?'cpc':'cpm';

	var field_name = document.getElementById('c_name');
	var field_country = document.getElementById('country');
	var field_website = document.getElementById('website');
	var field_keywords = document.getElementById('c_keywords');
	var field_dest_url = document.getElementById('c_dest_url');
	var field_headline = document.getElementById('c_headline');
	var field_description1 = document.getElementById('c_description1');
	var field_description2 = document.getElementById('c_description2');
	var field_disp_url = document.getElementById('c_disp_url');
	var field_budget = document.getElementById('c_budget_' + campaign_format);
	var field_bid = document.getElementById('c_bid_' + campaign_format);
	
	var field_fullname = document.getElementById('fullname');
	var field_youremail = document.getElementById('youremail');
	var field_username = document.getElementById('username');
	var field_newpassword = document.getElementById('newpassword');
	var field_newpassword2 = document.getElementById('newpassword2');
	
	var patt=/^\s*$/gi;
	// Perform validation checks on all campaign field data:
	// Check #1 - scan for empty fields
	alert_str = new Array();	
	if (patt.test(field_name.value))
		alert_str.push('Step 1: missing title');	
	
	if ($(field_country).find('option:selected').length == 0)
		alert_str.push('Step 2: missing country selection');
	
	if ($(field_website).find('option:selected').length == 0)
		alert_str.push('Step 3: missing website selection');
	
	if (campaign_format == 'cpc')
	{
		if(patt.test(field_keywords.value) || field_keywords.value.charAt(0) == '@')
			alert_str.push('Step 4: missing keywords');
	}
	
	if (patt.test(field_dest_url.value))
		alert_str.push('Step 5: missing destination url');
	
	if (patt.test(field_headline.value))
		alert_str.push('Step 5: missing ad title');
		
	if (patt.test(field_description1.value) && patt.test(field_description2.value))
		alert_str.push('Step 5: missing ad description');
	
	if (patt.test(field_disp_url.value))
		alert_str.push('Step 5: missing ad display URL');
	
	if (patt.test(field_budget.value))
	{
		alert_str.push('Step 6: missing daily budget');
	}else if(campaign_format == 'cpc')
	{
		if(Number(field_budget.value) < 0)
			alert_str.push('Step 6: negative daily budget');
	}else{
		if (Number(field_budget.value) < 5)
			alert_str.push('Step 6: minimum daily budget is $5.00');
	}
	
	if (patt.test(field_bid.value))
	{
		alert_str.push('Step 6: missing max. bid');
	}else  if(campaign_format == 'cpc')
	{
		if (Number(field_bid.value) < 0.1)
			alert_str.push('Step 6: minimum value for max. CPC bid is $0.10');
	}else{
		if (Number(field_bid.value) < 25)
			alert_str.push('Step 6: minimum value for max. CPM is $25.00');
	}
	
	if(MAX_CAMPAIGN_STEPS == 8) {		
		var userSignupLogin = 0;
		if (!patt.test(field_fullname.value)) userSignupLogin = 1;
		if (!patt.test(field_youremail.value)) userSignupLogin = 1;		
		if (!patt.test(field_newpassword2.value)) userSignupLogin = 1;			
		if (userSignupLogin == 0) {
			if (!patt.test(field_username.value)) userSignupLogin = 2;
			if (!patt.test(field_newpassword.value)) userSignupLogin = 2;
		}
		if (userSignupLogin == 1 || userSignupLogin == 0) {
			if (patt.test(field_fullname.value)) alert_str.push('Step ' + MAX_CAMPAIGN_STEPS + ': missing full name');	
			if (patt.test(field_youremail.value)) alert_str.push('Step ' + MAX_CAMPAIGN_STEPS + ': missing email');	 
			if (patt.test(field_username.value)) alert_str.push('Step ' + MAX_CAMPAIGN_STEPS + ': missing username');
			if (patt.test(field_newpassword.value)) alert_str.push('Step ' + MAX_CAMPAIGN_STEPS + ': missing password');
			if (patt.test(field_newpassword2.value)) alert_str.push('Step ' + MAX_CAMPAIGN_STEPS + ': missing password (re-type)');
		} else { // == 2
			if (patt.test(field_username.value)) alert_str.push('Step ' + MAX_CAMPAIGN_STEPS + ': missing username');
			if (patt.test(field_newpassword.value)) alert_str.push('Step ' + MAX_CAMPAIGN_STEPS + ': missing password');
		}
	}
	
	if(alert_str.length) {
		// Display an alert message detailing all errors.
		var html = '<ul class="errors-list">';
		for(var i=0; i<alert_str.length; i++)
			html += '<li>' + alert_str[i] + '</li>'
		html += '</ul>';
		$('#errors').html(html);
		//alert(alert_str);
		return false;
	} else {
		// Success! Passed all checks.
		return true;
	}			
}

/**
* Show next Campaign step and hide all the others.
* 
* @author odin.phillips@gmail.com
*/
function onCampaignNext() 
{
	if(g_campaign_step < (MAX_CAMPAIGN_STEPS-1)) {		
		g_campaign_step++;
			
		for(n=0; n<MAX_CAMPAIGN_STEPS; n++) {
			if(n == g_campaign_step) {
				show_step = document.getElementById(g_cstep[g_campaign_step]);
				show_step.style.visibility = 'visible';
				
			}
			else {
				hide_step = document.getElementById(g_cstep[n]);
				hide_step.style.visibility = 'hidden';
			}
		}
	}
	
	updateCampaignStep();
}

/**
* Show previous Campaign step and hide all the others.
* 
* @author odin.phillips@gmail.com
*/
function onCampaignBack()
{
	if(g_campaign_step > 0) {		
		g_campaign_step--;
			
		for(n=0; n<MAX_CAMPAIGN_STEPS; n++) {
			if(n == g_campaign_step) {
				show_step = document.getElementById(g_cstep[g_campaign_step]);
				show_step.style.visibility = 'visible';
			}
			else {
				hide_step = document.getElementById(g_cstep[n]);
				hide_step.style.visibility = 'hidden';
			}
		}
	}
	
	updateCampaignStep();
}

/**
* Perform campaign button updates, for when user is moving between steps.
*
* @author odin.phillips@gmail.com
*/
function updateCampaignStep()
{

	// Back 'off' overlay (grey) button.
	if (g_campaign_step == 0) {
		document.getElementById('c_backoff_button').style.visibility = 'visible';
	} else {
		document.getElementById('c_backoff_button').style.visibility = 'hidden';
	}
	
	// Next 'off' overlay (grey) button.
	if (g_campaign_step == (MAX_CAMPAIGN_STEPS-1)) {
		document.getElementById('c_nextoff_button').style.visibility = 'visible';
	} else {
		document.getElementById('c_nextoff_button').style.visibility = 'hidden';
	}
	
	// Show 'Submit' button on last step.
	if (g_campaign_step == (MAX_CAMPAIGN_STEPS-1)) {
		document.getElementById('c_submit_button').style.visibility = 'visible';
	} else {
		document.getElementById('c_submit_button').style.visibility = 'hidden';
	}
	
	// Update step numbers (1 '2' 3 4 5 etc.)
	numbersStr = '';	
	for (i=0; i<MAX_CAMPAIGN_STEPS; i++) {
		i == (MAX_CAMPAIGN_STEPS-1) ? sp = '' : sp = ' ';
		if (i == g_campaign_step) {
			numbersStr += ('<b><u>' + (i+1) + '</b></u>' + sp);			
		} 
		else {
			//numbersStr += ((i+1) + sp);
			numbersStr += '<span style=\"cursor:pointer\" onclick=\"javascript:onCampaignStep('+(i+1)+')\">'+(i+1)+'</span>' + sp;
		}
	}
	document.getElementById('c_step_numbers').innerHTML = numbersStr;
	//<span style=\"cursor:pointer\" onclick=\"javascript:onCampaignStep(2)\">2</span>
}

/**
* Changes the current campaign step. And updates the campaign step numbers at the 
* bottom i.e. the currently selected step number and sets the others so they are 
* clickable.
* < 1 '2' 3 4 5 etc. >
* 
* @param step	The target step we want to go to.
* @author odin.phillips@gmail.com
*/
function onCampaignStep(step)
{
	step--;
	if(step < 0 || step >= MAX_CAMPAIGN_STEPS) return;

	g_campaign_step = step;			
	for(n=0; n<MAX_CAMPAIGN_STEPS; n++) {
		if(n == g_campaign_step) {
			show_step = document.getElementById(g_cstep[g_campaign_step]);
			show_step.style.visibility = 'visible';
			
		}
		else {
			hide_step = document.getElementById(g_cstep[n]);
			hide_step.style.visibility = 'hidden';
		}
	}		
	updateCampaignStep();
}

/**
* Switches 'on' the special (orange underlined text) sub pop-up
*
* @author odin.phillips@gmail.com
*/
function onSubMouseOver(evt, ref_div_id, div_id)
{	
	//ref = document.getElementById(ref_div_id);	
		
	var posx = 0;
	var posy = 0;
	if (!evt) var evt = window.event;
	if (evt.pageX || evt.pageY) 	{
		posx = evt.pageX;
		posy = evt.pageY;
	}
	else if (evt.clientX || evt.clientY) 	{
		posx = evt.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		posy = evt.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}

	x = /*ref.style.left +*/ posx - 52;// + document.screenX;	
	y = posy - 246;/*- ref.style.top;*/// + document.screenY;	;
	
	// Switch div on at mouse-offseted location.
	obj = document.getElementById(div_id);
	obj.style.left = (x + 52) + 'px';
	obj.style.top = (y + 122) + 'px';
	obj.style.visibility = 'visible';
}

/**
* Switches 'off' the special (orange underlined text) sub pop-up
*
* @author odin.phillips@gmail.com
*/
function onSubMouseOut(div_id)
{
	document.getElementById(div_id).style.visibility = 'hidden';
}
 
/**
* Test a URL that was entered in a form Input element.
* 
* @author odin.phillips@gmil.com
*/
function onCampaignTestURL(input_id)
{
	obj = document.getElementById(input_id);	
	testURL = 'http://' + obj.value; 
	window.open(testURL,'_blank');
}

updateCampaignSteps();