/* General use in CC */
var TD_COUNT_COL = 0;
var TD_COUNTRY = 1;
var TD_STATE = 2;
var TD_CITY = 3;
var LOCATION_LIMIT = 3;
var locationCount = 0;
var countryArr = new Array();
var stateArr = new Array();

function getAjaxServices(which){
	var serviceURL = "/services/casting_call_services.php";
	var countryCode = $("#idCcCountry").val();
	var countryCodeFirst = $("#idCcCountry option:first"); //work around for adding all selection
	
	var stateId = $("#idCcState").val();
	switch(which){
		case "state":	
			var ss = $("#idCcState");			
			var sc = $("#idCcCity");
			ss.empty();					
			sc.empty();		
			 $.ajax({
			   type: "POST",
			   url: serviceURL,
			   data: "fm_action=state&country_code=" + countryCode + "&first_option=" + countryCodeFirst.text(),
			   success: function(options){
			    	ss.append(options);
			   }
			 });
			break;
			
		case "city":
			var sc = $("#idCcCity");
			sc.empty();			
			 $.ajax({
			   type: "POST",
			   url: serviceURL,
			   data: "fm_action=city&state_id="+ stateId + "&first_option=" + countryCodeFirst.text(),
			   success: function(options){
			    	sc.append(options);
			   }
			 });
			break;
	} //switch
} //getAjaxServices

function initGeoBlock(){
	$("#idCcCountry").change(function(){
		getAjaxServices('state');
	});	
	
	$("#idCcState").change(function(){
		getAjaxServices('city');	
	});	
	
	//getAjaxServices('state'); //DEFAULT TO US STATES
} //initGeoBlock()

function initGeoButton(){
	$("#idCcCity").change(function(){
		var locationBtn = 	$("#idCcAddButton");
		if(isSelectedGeo() && !isLocationOverLimit()){
			locationBtn.removeAttr("disabled");			
			toogleLocationBtn("enable");
		} else {
			locationBtn.attr("disabled", "disabled");				
			toogleLocationBtn("disable");
		}
	});	
}

function toogleLocationBtn(which){
	var locationBtn = 	$("#idCcAddButton");
	if(which == "enable"){
		locationBtn.removeClass("ccLocationDisableBtn");	
		locationBtn.addClass("ccLocationBtn");	
	} else {
		locationBtn.removeClass("ccLocationBtn");	
		locationBtn.addClass("ccLocationDisableBtn");	
	}
} //toogleLocationBtn

function inArray(needle, arr){
	for (i=0; i < arr.length; i++){
		thisValue = arr[i];
		if(thisValue == needle){
			return true;
			break;	
		}
	} //for	
	
	return false;
} //inArray

function removeGeo(){	
	var trNode = this.parentNode.parentNode;
	var tNode = trNode.parentNode;
	tNode.removeChild(trNode);
	adjustGeoCount();
	if(locationCount >0){
		locationCount--;
	}
	if(!isLocationOverLimit()){
		$("#idCcAddButton").removeAttr("disabled");
		toogleLocationBtn("enable");
	} else {
		toogleLocationBtn("disable");	
	}
	
}

function presetRemoveGeo(){
	$(".removeGeo").click(removeGeo);	
}

function setGeoCount(){
	var locationTable = $el("idCcLocationTable");
	var trs = locationTable.getElementsByTagName("TR");
	locationCount = trs.length-1; //subtract first rows
}

function preconfig(){
	setGeoCount();
	presetRemoveGeo();
}

////////////////////// END - General use in all CC related /////////////////////////////////////

////////////////////// used in Post new Casting Call /////////////////////////////////////////

function initPostCastingCall(){
	initGeoBlock();	
	initCcPreview();
	doJQueryTooltips();
	initDate();
	initPaymentBox();
} //initPostCastingCall

function initPaymentBox(){
	var compOption = $("input[name='c_compensation']");
	var compBox = $("#compPayAmount");
	if(compOption[2].checked){
		compBox.show("fadeout");
	}
	
	compOption.click(function(){
		var thisVal = this.value;
///		var compBox = $("#compPayAmount");
		if(thisVal == 2){
			compBox.show("fadeout");
		} else {
			compBox.hide("fadein");	
		}
	});
}

function initNewCcForm(){
	$("#idNewCcForm").submit(function(){
		return storeGeo(false);					
	});
	
} //initNewCcForm - trigger when form sumbitted
	
	
function initAddLocation(){	
	btnLocation = $("#idCcAddButton");
	btnLocation.click(processLocation);
}

function processLocation(){
	var msg = "";	
	result = isSelectedGeo();
	if(!result){
		msg = "Country, States and City must be selected";
	}
	
	
	var geoObj = isOkToAddGeo();
	if(result && !geoObj.result){
		msg = geoObj.msg;
		result = false;
	}
	
	if(result && isLocationOverLimit()){
		msg = "Can not add more than 3 locations.";
		result = false;
	}
	if(result){
		createGeo();
		locationCount++;		
	} else {
		alert(msg);
	}
	
	if(isLocationOverLimit()){
		$("#idCcAddButton").attr("disabled", "disabled");
		toogleLocationBtn("disable");
	} else {
		toogleLocationBtn("enable");	
	}
} //processLocation()

function isLocationOverLimit(){
	return (locationCount >= LOCATION_LIMIT);
}

function isOkToAddGeo(){
	var rObj = new Object;
	var tempStateArr = new Array();
	var tempCountryArr = new Array();
	rObj.result = true;
	rObj.msg = "";
	var selectedCountry = getSelectedCountry().v;
	var selectedState = getSelectedState().v;
	var selectedCity = getSelectedCity().v;
	
	var locationTable = $el("idCcLocationTable");
	var trs = locationTable.getElementsByTagName("TR");
	//skip th - section title
	for(iTr =1; iTr < trs.length; iTr++){
		var thisCountryCode = "";
		var thisStateCode = "";
		var thisCityCode = "";
		var thisTr = trs[iTr];
		var tds = thisTr.getElementsByTagName("TD");
		if(tds.length > 0){
			thisCountryCode = tds[TD_COUNTRY].getAttribute("value");
			thisStateCode = tds[TD_STATE].getAttribute("value");
			thisCityCode = tds[TD_CITY].getAttribute("value");
		}
		
		if(selectedCountry == thisCountryCode && selectedState == thisStateCode && selectedCity == thisCityCode){
			rObj.result = false;
			rObj.msg = "Already added this location.";
			break;	
		}		
			
	} //tr loop	
	return rObj;
} //isOkToAddGeo

function storeGeo(storeAsPreview){
	var locationTable = $el("idCcLocationTable");
	var trs = locationTable.getElementsByTagName("TR");	
	var tempGeo = "";
	var delimiter = "";
	var result = false;
	
	//skip th - section title
	for(iTr =1; iTr < trs.length; iTr++){
		var thisCountryCode = "";
		var thisStateCode = "";
		var thisCityCode = "";
		var thisTr = trs[iTr];
		var tds = thisTr.getElementsByTagName("TD");
		if(tds.length > 0){
			if(storeAsPreview){
				thisCountryCode = tds[TD_COUNTRY].innerHTML;
				thisStateCode = tds[TD_STATE].innerHTML;
				thisCityCode = tds[TD_CITY].innerHTML;
			} else {
				thisCountryCode = tds[TD_COUNTRY].getAttribute("value");
				thisStateCode = tds[TD_STATE].getAttribute("value");
				thisCityCode = tds[TD_CITY].getAttribute("value");
			}
		}
		if(storeAsPreview){
			tempGeo = tempGeo + delimiter + thisCityCode + ", " + thisStateCode + ", " + thisCountryCode;
		} else {
			tempGeo = tempGeo + delimiter + thisCountryCode + "," + thisStateCode + "," + thisCityCode;	
		}
	 	delimiter = "|";
	} //tr loop
	
	if(tempGeo != ""){
		$("#idCcSelectedGeo").val(tempGeo);	
		result = true;
	} else {
		alert("You must selected atleast one location");	
	}
	
	//alert($("#idCcSelectedGeo").val()); //for debug 
	return result;
} //storeGeo -- added selected geo to hidden


function createGeo(){
	var countryObj = getSelectedCountry();
	var stateObj = getSelectedState();
	var cityObj = getSelectedCity();
	var aa = $("#idCcLocationTable").append("<tr><td class='numberCell'>&nbsp;</td><td value='" + countryObj.v+ "'>" + countryObj.t + "</td><td value='" + stateObj.v + "'>"+ stateObj.t + "</td><td value='" + cityObj.v + "'>" + cityObj.t + "</td><td><a href='javascript:void(0)' class='removeGeo'>remove</a></td></tr>");	
		
	geoTracking(countryObj.v, stateObj.v);
	adjustGeoCount();
	$(".removeGeo").click(removeGeo);	
} //createGeo

function adjustGeoCount(){
	var locationTable = $el("idCcLocationTable");
	var trs = locationTable.getElementsByTagName("TR");	
	for(iTr =1; iTr < trs.length; iTr++){
		var thisTr = trs[iTr];	
		var tds = thisTr.getElementsByTagName("TD");
		tds[TD_COUNT_COL].innerHTML = iTr + ". ";		
	}
} //adjustGeoCount

function geoTracking(country, state){
	if(!inArray(country, countryArr)){
		countryArr.push(country);
	}
	//alert(inArray(state, stateArr) + " " + state);
	if(!inArray(state, stateArr)){
		stateArr.push(state);
	}
} //geoTracking()


function getSelectedCountry(){
	var result = new Object;
	result.v = "";
	result.t = "";
	selectedObj = $("#idCcCountry option:selected");
	if(selectedObj.val() != ""){
		result.v = selectedObj.val();	
		result.t = selectedObj.text();	
	}
	return result;
} //getSelectedCountry()

function getSelectedState(){	
	var result = new Object;
	result.v = "";
	result.t = "";
	selectedObj = $("#idCcState option:selected");
	if(selectedObj.val() != ""){
		result.v = selectedObj.val();	
		result.t = selectedObj.text();	
	}
	return result;
}

function getSelectedCity(){
	var result = new Object;
	result.v = "";
	result.t = "";
	selectedObj = $("#idCcCity option:selected");
	if(selectedObj.val() != ""){
		result.v = selectedObj.val();	
		result.t = selectedObj.text();		
	}
	return result;
} //getSelectedCity()

function isSelectedGeo(){		
	var country = getSelectedCountry().v;
	var state = getSelectedState().v;
	var city = getSelectedCity().v;
	return (country != "" && state != "" && city != "")?true: false;	
}

////////////////////// END - used in Post new Casting Call /////////////////////////////////////////

////////////////////// used in Post new TN Casting Call /////////////////////////////////////////

function initPostCastingCallTN(){
	initGeoBlock();
	initGeoButton();
	initAddLocation();
	initNewCcTnForm();
	preconfig();
	initCcPreview();
	doJQueryTooltips();
	initDate();
	initPaymentBox();
} //initPostCastingCallTN

function initNewCcTnForm(){
	$("#idNewCcTnForm").submit(function(){
		return storeGeo(false);					
	});
	
} //initNewCcForm - trigger when form sumbitted

////////////////////// END - used in Post new TN Casting Call /////////////////////////////////////////

////////////////////// used in Post new LA Casting Call /////////////////////////////////////////

function initPostCastingCallLA(){
	initGeoBlock();
	initCcPreview();
	doJQueryTooltips();	
	initPaymentBox();
} //initPostCastingCallTN

function initNewCcLaForm(){
	$("#idNewCcLaForm").submit(function(){
		return storeGeo(false);					
	});
	
} //initNewCcForm - trigger when form sumbitted

////////////////////// END - used in Post new LA Casting Call /////////////////////////////////////////


////////////////////// START - used in Edit Casting Call for all type/////////////////////////////////////////

function initEditCastingCall(which){
	initGeoBlock();
	if(which == "tn"){
		initGeoButton();
		initAddLocation();
		initEditCcForm();
		preconfig();
	}
	if(which != "la"){
		initDate();	
	}
	initCcPreview();
	doJQueryTooltips();
	initPaymentBox();
} //initEditCastingCall


function initEditCcForm(){
	$("#idEditCcForm").submit(function(){
		return storeGeo(false);					
	});
	
} //initNewCcForm - trigger when form sumbitted
////////////////////// END - used in Edit Casting Call for all type/////////////////////////////////////////



////////////////////// used in Search / Main Casting Call /////////////////////////////////////////

function initCcSearch(){
	toggleSearchOption();
	toogleSearchType();
	initGeoBlock();
	doJQueryTooltips();
	initDate();
	initPaymentBox();
} //initCcSearch

function initDate(){
	var startDate = $("#dp-normal-1");
	startDate.change(toggleDate);
}
function toggleDate(){
	var startDate = this;
	var endDate = $("#dp-normal-2");	
	if(isValidDate(startDate.value.trim())){		
		var msecsInADay = 86400000;
		var tempDate = new Date(startDate.value);
		var endDateTimestamp = new Date(tempDate.getTime() + msecsInADay);
		var m = "" + (endDateTimestamp.getMonth()+1);
			m = (m.length < 2)? "0" + m : m;			
		var d = "" + endDateTimestamp.getDate();		
			d = (d.length < 2)?"0" + d : d;			
		var y = endDateTimestamp.getFullYear();
		
		endDate.val(m + "/" + d + '/' + y);		
	}
}


function toggleSearchOption(){
	var AdvanceElm = $("#advanceSearch a");
	var fmBasic = $("#basicAction");
	var showAdvanced = $("input[name='show_advanced']");
	AdvanceElm.click(function(){
		$("#advanceOption").toggle("normal");
		var currLabel = AdvanceElm.text();
		if(currLabel == "Show Advanced [+]"){
			AdvanceElm.text("Hide Advanced [-]");
			fmBasic.hide();
			showAdvanced.val(1);
		} else {
			resetAdvanceField();
			AdvanceElm.text("Show Advanced [+]");
			fmBasic.show();
			showAdvanced.val(0);
		}
	}
	);
} //toogleSearchOption

function resetAdvanceField(){
	$(".w8em").val("");
	var tnInclude = $("input[name='search_include_tn']");
	tnInclude[2].checked = true;
	
	var nudity = $("input[name='c_18']");
	for(i=0; i < nudity.length; i++){
		nudity[i].checked = false;
	}	
	
	var comp = $("input[name='c_compensation']");	
	for(i=0; i < comp.length; i++){
		comp[i].checked = false;
	}	
	
	var keyword = $("input[name='search_keyword']");
	keyword.val("");
		
	var keyword = $("input[name='search_details']");
	keyword[0].checked = false;
		
	var sortby = $("input[name='search_sortby']");	
	for(i=0; i < sortby.length; i++){
		sortby[i].checked = false;
	}	
	
	var mmId = $("input[name='search_mm_id']");
	mmId.val("");
	
	var mmName = $("input[name='search_mm_name']");
	mmName.val("");
} //resetAdvanceField()

function toogleSearchType(){
	$("input[name='search_type']").click(function(){
		$("#idSearchCasting")[0].selectedIndex = -1;
		thisVal = this.value;		
		toogleInclude(thisVal);
	});	
} //toogleSearchType

function toogleInclude(which){	
	if(which == "looking for"){
		$("#idIncludeC").css("display", "none");				
		$("#idIncludeNC").css("display", "");					
	} else {
		$("#idIncludeNC").css("display", "none");				
		$("#idIncludeC").css("display", "");									
	}
} //toogleInclude

////////////////////// END - used in Search / Main Casting Call /////////////////////////////////////////

function $el(id){
	return document.getElementById(id);	
} //for some reason JQUERY won't work with some feature, need this for some customs

function initCcPreview(){	
	var previewBtn = $("#ccPreview");
	previewBtn.click(doCcPreview);
}

function doCcPreview(){	
	var fm = this.form;
	var ccTypeArr = new Array();
	var ccTypes = "";
	var urlParams = [];
	var cp = this.getAttribute("cp");
	var cc18 = "";
	var ccCompensation = "";
	urlParams.push("cp=" + cp);
	var foundRadioArr = new Array();
	
	for(i=0; i < fm.elements.length; i++){
		
		thisElm = fm.elements[i];
		if(thisElm.type == "hidden"){
			continue;	
		}

		if(thisElm.name == 'm_casting_type[]'){
			for(j=0; j < thisElm.options.length; j++){
				if(thisElm.options[j].selected){
					ccTypeArr.push(thisElm.options[j].text);
				}
			}
			continue;
		}
		
		if(thisElm.type == "radio"){						
			if(jQuery.inArray(thisElm.name, foundRadioArr) != -1){
				continue;
			}
			
			foundRadioArr.push(thisElm.name);
			var thisRadio = fm.elements[thisElm.name];
			for(j=0; j < thisRadio.length; j++){				
				if(thisRadio[j].checked == true){
					urlParams.push(thisElm.name + "=" + encodeURI(thisRadio[j].value));					
				}
			}			
			continue;	
		}

		switch (thisElm.tagName){
			case "INPUT":
			case "TEXTAREA":				
					thisValue = thisElm.value.replace(new RegExp(/&/), "%26");
					urlParams.push(thisElm.name + "=" + encodeURI(thisValue));								
				break;
			case "SELECT":
				if(thisElm.name == 'm_casting_type[]'){continue;}
				urlParams.push(thisElm.name + "=" + encodeURI(thisElm.options[thisElm.selectedIndex].text));
				break;
		}
		
	} //outter for
	
	if(ccTypeArr.length > 0){
		ccTypes = ccTypeArr.join("|");
	}
	
	urlParams.push("m_casting_type=" + encodeURI(ccTypes));
	
	if(cp == "tn"){
		storeGeo(true); //store seleted geo into hidden fields
		var selectedGeo = $("#idCcSelectedGeo").val();	
		urlParams.push("selected_geo=" + encodeURI(selectedGeo));
	}
	
	var previewUrl = "/castingcalls_preview.php?height=500&width=800&" + urlParams.join("&");
		
	tb_show('Casting Calls - Preview',previewUrl , false);
} //doCcPreview

function doJQueryTooltips(){
	$(".jQueryTooltips").tooltip();
}

function initCastingAlert(){	
	initAlertDelete();
	initAlertViewFilter();
} //initCastingAlert

function initAlertViewFilter(){	
	//alertViewFilter
	$("a.alertViewFilter").click(function(){
		var viewURL = "/castingcalls_alert_view_filter.php?height=450&width=540&alert_id=" + this.getAttribute("alert_id");
		tb_show('Casting Calls - Filter Details',viewURL , false);
	});
} //initAlertViewFilter

function initAlertDelete(){
	$("a.alertDelete").click(function(){
		var deleteConfirm = confirm("Are you sure you want to delete this setting?");
		if(deleteConfirm){
			var deleteURL = "/castingcalls_alert_delete.php?alert_id=" + this.getAttribute("alert_id");
			window.location.href=deleteURL;
		}
	});	
}

function initAlertSetting(){
	$("a#alertSubmit").click(function(){
		var ahref = this.href;
		var alertName = $("input#alertName").val();
		this.href= ahref + "&alert_name=" + alertName;
	}
	);	
}

jQuery.fn.extend(
{
	trim: function(){
		return jQuery.trim(this);
	}	
}
);