var regExEmail = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
var regExWebsite = /^(http:\/\/)?\w+([\.-]?\w+)*\w+([\.-]?\w+)*(\.\w+)+(\/)?(\w+)?$/;
var regExReq = /.+/;
var regExReq6 = /.{6}/;
var regExNum = /^[\d]+$/;
var hasErrors = false;
var url = "ajax.aspx";
var sections = new Array();
sections[0] = {'code':'age', 'cost':0, 'parent':null, 'subtabs':false, 'subtabs_checked':0};
sections[1] = {'code':'min', 'cost':0, 'parent':null, 'subtabs':false, 'subtabs_checked':0};
sections[2] = {'code':'ser', 'cost':0, 'parent':null, 'subtabs':false, 'subtabs_checked':0};
sections[3] = {'code':'des', 'cost':0, 'parent':null, 'subtabs':false, 'subtabs_checked':0};
sections[4] = {'code':'med', 'cost':0, 'parent':null, 'subtabs':true, 'subtabs_checked':0};
sections[5] = {'code':'cin', 'cost':0, 'parent':'med', 'subtabs':false, 'subtabs_checked':0};
sections[6] = {'code':'dir', 'cost':0, 'parent':'med', 'subtabs':false, 'subtabs_checked':0};
sections[7] = {'code':'mag', 'cost':0, 'parent':'med', 'subtabs':false, 'subtabs_checked':0};
sections[8] = {'code':'new', 'cost':0, 'parent':'med', 'subtabs':false, 'subtabs_checked':0};
sections[9] = {'code':'out', 'cost':0, 'parent':'med', 'subtabs':false, 'subtabs_checked':0}; 
sections[10] = {'code':'rad', 'cost':0, 'parent':'med', 'subtabs':false, 'subtabs_checked':0};
sections[11] = {'code':'tel', 'cost':0, 'parent':'med', 'subtabs':false, 'subtabs_checked':0};
sections[12] = {'code':'web', 'cost':0, 'parent':'med', 'subtabs':false, 'subtabs_checked':0};
sections[13] = {'code':'tvc', 'cost':0, 'parent':null, 'subtabs':true, 'subtabs_checked':0};
sections[14] = {'code':'ani', 'cost':0, 'parent':'tvc', 'subtabs':false, 'subtabs_checked':0};
sections[15] = {'code':'aud', 'cost':0, 'parent':'tvc', 'subtabs':false, 'subtabs_checked':0};
sections[16] = {'code':'loc', 'cost':0, 'parent':'tvc', 'subtabs':false, 'subtabs_checked':0};
sections[17] = {'code':'pos', 'cost':0, 'parent':'tvc', 'subtabs':false, 'subtabs_checked':0};
sections[18] = {'code':'pro', 'cost':0, 'parent':'tvc', 'subtabs':false, 'subtabs_checked':0};
sections[19] = {'code':'voi', 'cost':0, 'parent':'tvc', 'subtabs':false, 'subtabs_checked':0};

var load_small = "<div class='loading'><img src='images/loading.gif' /><br />Updating... please wait</div>";
var dropdown_loading = "<label>--- Loading ---<br/ ><select disabled='disabled'><option value='0'>--- Loading... please wait ---</option></select></label>";
var dropdown_select = "<label>Sub category<br/ ><select disabled='disabled'><option value='0'>--- Please select a category ---</option></select></label>";

window.onload = function()
{
	GetSubTabsChecked();
	SetAllSubtotals();
	SelectFirstTab();
	ValidateAll();
}

function findSection(prop, val, returnID)
{
    for (var i = 0; i < sections.length; i++)
    {
        if (eval('sections['+i+'].'+prop) == val) 
        {
            if (returnID) return i;
            else return sections[i];
        }
    }
    return null;
}

function SaveSection()
{
    alert("This Section has been successfully saved.\r\n\r\nWhen you have finished editing all the Sections you wish to be listed in, be sure to click the 'Confirm my listings' button at the bottom of this page.");
}

function AddError(msg)
{
    hasErrors = true;
    $("errors").innerHTML += msg + "<br />";
}

function vf(obj, regEx)
{
	if (!obj.value.match(regEx))
	{
	    obj.style.backgroundImage = "url(images/hatch.gif)";
	    
		return false;
	}
	else
	{
	    obj.style.backgroundImage = "none";
	    
		return true;
	}
}

function ValidateAll()
{
    hasErrors = false;
    Element.hide("errors");
    $("errors").innerHTML = "<h3>List of errors to fix before saving:</h3>";
    if ($("authenticate"))
    {
        if (!vf($("authenticate"), "^" + $F("user_id") + "$")) AddError("Please fill in your authentication code in the 'New Registration' field above.");
    }
    
    var totalChecked = 0;
    for (var i = 0; i < sections.length; i++)
	{
		if (!sections[i].subtabs) 
		{
		    if($(sections[i].code + "_chk").checked)
		    {
		        totalChecked++;
			    Validate(sections[i].code);
			}
		}
	}
	if (totalChecked == 0)
	{
	    AddError("Please select at least one listing from the 'Your Listings' area.");
	}
	if (hasErrors) 
	{
	    //$("listings_area").style.borderColor = "#B30101";
	    Element.show("errors");
	}
	else 
	{
	    //$("listings_area").style.borderColor = "#000";
	    Element.hide("errors");
	}
}

function Validate(tab)
{
    var specify = "You need to specify a";
    
    if (!vf($(tab + "_c_companyname"), regExReq)) AddError(specify + " company name.");
    if (!vf($(tab + "_c_postal_street"), regExReq)) AddError(specify + " street address.");
    if (!vf($(tab + "_c_postal_city"), regExReq)) AddError(specify + " city.");
    if (!vf($(tab + "_c_postal_country"), regExReq)) AddError(specify + " country.");
    if (!$(tab + "_c_physical_chk").checked)
    {
        if (!vf($(tab + "_c_physical_street"), regExReq)) AddError(specify + " street address.");
	    if (!vf($(tab + "_c_physical_city"), regExReq)) AddError(specify + " city.");
	    if (!vf($(tab + "_c_physical_country"), regExReq)) AddError(specify + " country.");
    }
    if (!vf($(tab + "_c_phone"), regExReq)) AddError(specify + " phone number.");
    if ($(tab + "_c_email").value.length > 0 && !vf($(tab + "_c_email"), regExEmail)) AddError(specify + " valid email address (or none at all).");
    if ($(tab + "_c_website").value.length > 0 && !vf($(tab + "_c_website"), regExWebsite)) AddError(specify + " valid website (or none at all).");
    if ($(tab + "_c2_chk").checked)
    {
        if (!vf($(tab + "_c2_postal_street"), regExReq)) AddError(specify + " street address.");
	    if (!vf($(tab + "_c2_postal_city"), regExReq)) AddError(specify + " city.");
	    if (!vf($(tab + "_c2_postal_country"), regExReq)) AddError(specify + " country.");
	    if (!$(tab + "_c2_physical_chk").checked)
	    {
	        if (!vf($(tab + "_c2_physical_street"), regExReq)) AddError(specify + " street address.");
    	    if (!vf($(tab + "_c2_physical_city"), regExReq)) AddError(specify + " city.");
    	    if (!vf($(tab + "_c2_physical_country"), regExReq)) AddError(specify + " country.");
	    }
	    if (!vf($(tab + "_c2_phone"), regExReq)) AddError(specify + " phone number.");
	    if ($(tab + "_c2_email").value.length > 0 && !vf($(tab + "_c2_email"), regExEmail)) AddError(specify + " valid email address (or none at all).");
	    if ($(tab + "_c2_website").value.length > 0 && !vf($(tab + "_c2_website"), regExWebsite)) AddError(specify + " valid website (or none at all).");
    }
    if ($(tab + "_nopeople") != null) AddError("Please add at least one person to each selected listing.");
    switch (tab)
	{
		case "age":
		    var serArray = new Array("full", "sales", "interactive", "direct", "brand", "design", "pr", "marketing", "event", "planning");
		    var serSelected = false;
		    for (var i = 0; i < serArray.length; i++)
		    {
		        if ($("age_ser_" + serArray[i]).checked) serSelected = true;
		    }
		    if (!serSelected) AddError("Please select at least one service in the Agency listing section.");
		    if ($("age_noclients") != null) AddError("Please add at least one client to the Agency listing section.");
			break;
		case "min":
		    if ($("min_noclients") != null) AddError("Please add at least one client to the Media Independent listing section.");
			break;
		case "des":
			break;
		case "ser":
		    var serCatsSelected = false;
		    for (var i = 1; i <= 19; i++)
		    {
		        if ($("ser_cats_" + i).checked) serCatsSelected = true;
		    }
		    if (!serCatsSelected) AddError("Please select at least one category in the Services to Agencies listing section.");
			break;
		case "cin":
		case "mag":
		case "new":
		case "out":
		case "rad":
		case "tel":
		case "web":
		case "ani":
		case "aud":
		case "loc":
		case "pos":
		case "pro":
		case "voi":
		    
		    break;
    }
}

function DoSubmit()
{
    if (hasErrors)
    {
        alert("You have missed out one or more compulsory fields.\r\nPlease review the list of errors above before saving.");
    }
    else
    {
        Element.hide('wrap');
        Element.show('smallwrap');
        document.forms[0].submit();
    }
}

function LogOut()
{
    window.location = "login.aspx";
}

function Textify(text)
{
    return "<textarea cols='100' rows='30'>" + text + "</textarea>";
}

function Wait(bool)
{
    if (bool) document.body.style.cursor='wait';
    else document.body.style.cursor='default';
}

function SelectFirstTab()
{
    for (var i = 0; i < sections.length; i++)
	{
		if (!sections[i].parent && !sections[i].subtabs && $(sections[i].code + "_chk").checked)
		{
			ShowTab(sections[i].code);
			return;
		}
		if (sections[i].parent && $(sections[i].code + "_chk").checked)
		{
		    ShowTab(sections[i].parent);
		    ShowSubTab(sections[i].code);
		    return;
		}
	}
	ShowTab("age");
}

function ShowError(error)
{
    alert(error);
}

function GetAllPeople()
{
	for (var i = 0; i < sections.length; i++)
	{
	    //alert("people " + sections[i].code);
		if (sections[i].code != "med") GetPeople(sections[i].code);
	}
}
function SetAllSubtotals()
{
	for (var i = 0; i < sections.length; i++)
	{
		if (sections[i].code != "med" && sections[i].code != "tvc") OptionsChanged(sections[i].code);
	}
}

function ChangeClass(obj, newclass)
{
	obj.setAttribute("class", newclass);
	obj.setAttribute("className", newclass);
}

function GetSubTabsChecked()
{
	for (var i = 0; i < sections.length; i++)
	{
	    if (sections[i].parent && $(sections[i].code + "_chk").checked)
		{
		    sections[findSection('code', sections[i].parent, true)].subtabs_checked++;
			OptionsChanged(sections[i].code)
		}
	}
}

function ToggleSubtotals(tab, show)
{
	style = "none";
	if (show) style = "inline";
	$(tab + "_subtotal1").style.display = style;
	$(tab + "_subtotal2").style.display = style;
}

function TabCheck(tab)
{
    ValidateAll();
	OptionsChanged(tab)
	if ($(tab + "_chk").checked) 
	{
		Element.show(tab + "_fields");
		ChangeClass($(tab + "_tab"), "main_tab_enabled_selected");
		ToggleSubtotals(tab, true);
	}
	else 
	{
		ToggleSubtotals(tab, false);
		Element.hide(tab + "_fields");
		ChangeClass($(tab + "_tab"), "main_tab_selected");
	}
}

function SubTabCheck(tab)
{
    ValidateAll();
	OptionsChanged(tab);
	var subtab = findSection('code', tab);
	if ($(tab + "_chk").checked) 
	{
	    sections[findSection('code', subtab.parent, true)].subtabs_checked++;
		Element.show(tab + "_fields");
		ChangeClass($(tab + "_tab"), "main_tab_enabled_selected");
		ChangeClass($(subtab.parent+"_tab"), "main_tab_enabled_selected");
		ToggleSubtotals(tab, true);
	}
	else 
	{
		ToggleSubtotals(tab, false);
		sections[findSection('code', subtab.parent, true)].subtabs_checked--;
		Element.hide(tab + "_fields");
		ChangeClass($(tab + "_tab"), "main_tab_selected");
		if (findSection('code', subtab.parent).subtabs_checked <= 0)
		{
			ChangeClass($(subtab.parent+"_tab"), "main_tab_selected");
		}
	}
}

function HideAllTabs()
{
	for (var i = 0; i < sections.length; i++) 
	{
		if (!sections[i].parent)
		{
			if (!sections[i].subtabs && $(sections[i].code + "_chk").checked)
			{
				ChangeClass($(sections[i].code + "_tab"), "main_tab_enabled");
			}
			else
			{
				ChangeClass($(sections[i].code + "_tab"), "main_tab");
			}
			Element.hide(sections[i].code);
		}
	}
	
	if (findSection('code', 'med').subtabs_checked > 0) ChangeClass($("med_tab"), "main_tab_enabled");
	else ChangeClass($("med_tab"), "main_tab");
	
	if (findSection('code', 'tvc').subtabs_checked > 0) ChangeClass($("tvc_tab"), "main_tab_enabled");
	else ChangeClass($("tvc_tab"), "main_tab");
}

function ShowTab(tab)
{
	HideAllTabs();
	HideAllSubTabs();
	Element.show(tab);
	if (tab == "med")
	{
		ShowSubTab("cin");
		if (findSection('code', 'med').subtabs_checked > 0) ChangeClass($(tab + "_tab"), "main_tab_enabled_selected"); 
		else ChangeClass($(tab + "_tab"), "main_tab_selected"); 
	}
	else if (tab == "tvc")
	{
		ShowSubTab("ani");
		if (findSection('code', 'tvc').subtabs_checked > 0) ChangeClass($(tab + "_tab"), "main_tab_enabled_selected");
		else ChangeClass($(tab + "_tab"), "main_tab_selected"); 
	}
	else
	{
		if ($(tab + "_chk").checked)
		{
			ChangeClass($(tab + "_tab"), "main_tab_enabled_selected");
			Element.show(tab + "_fields");
		}
		else
		{
			ChangeClass($(tab + "_tab"), "main_tab_selected");
			Element.hide(tab + "_fields");
		}
		GetPeople(tab);
		if (tab == "min" || tab == "age") GetClients(tab);
	}
}

function HideAllSubTabs()
{
	for (var i = 0; i < sections.length; i++) 
	{
		if (sections[i].parent)
		{
			if ($(sections[i].code + "_chk").checked)
			{
				ChangeClass($(sections[i].code + "_tab"), "sub_tab_enabled");
			}
			else
			{
				ChangeClass($(sections[i].code + "_tab"), "sub_tab");
			}
			Element.hide(sections[i].code);
		}
	}
}

function ShowSubTab(tab)
{
	HideAllSubTabs();
	Element.show(tab);
	if ($(tab + "_chk").checked)
	{
		ChangeClass($(tab + "_tab"), "sub_tab_enabled_selected");
	}
	else
	{
		ChangeClass($(tab + "_tab"), "sub_tab_selected");
	}
	if (!$(tab + "_chk").checked) Element.hide(tab + "_fields");
	else 	Element.show(tab + "_fields");
	GetPeople(tab);
}

function OptionsChanged(tab)
{
	if($(tab + "_chk").checked)
	{
		switch (tab)
		{
			case "age":
				if ($("age_silver").checked)
				{
					$(tab + "_upload_area").style.display = "none";
					//UpdateSubtotal(tab, 0);
					UpdateSubtotal(tab, age_silver_price);
				}
				else if ($("age_gold").checked)
				{
					$(tab + "_upload_area").style.display = "block";
					//UpdateSubtotal(tab, 300);
					UpdateSubtotal(tab, age_gold_price);
				}
				break;
			case "min":
				if ($("min_silver").checked)
				{
					$(tab + "_upload_area").style.display = "none";
					//UpdateSubtotal(tab, 0);
					UpdateSubtotal(tab, min_silver_price);
				}
				else if ($("min_gold").checked)
				{
					$(tab + "_upload_area").style.display = "block";
					//UpdateSubtotal(tab, 300);
					UpdateSubtotal(tab, min_gold_price);
				}
				break;
			case "des":
				//UpdateSubtotal(tab, 450);
				UpdateSubtotal(tab, des_price);
				break;
			case "ser":
				//alert("item checked");
			    var cats = 0;
				for (var i = 1; i <= 19; i++)
                {
                    if ($("ser_cats_" + i).checked) cats += 1;
                }
                if (cats < 2)
                {
                	//alert("less than two");
                    //UpdateSubtotal(tab, 450);
                    UpdateSubtotal(tab, ser_base_price);
                }
                else
                {
                	//alert("two or more");
                    //UpdateSubtotal(tab, 450 + ((cats - 1) * 250));
                    UpdateSubtotal(tab, ser_base_price + ((cats - 1) * ser_increment_price));
                }
				break;
			case "cin":
			case "dir":
			case "mag":
			case "new":
			case "out":
			case "rad":
			case "tel":
			case "web":
		    case "ani":
		    case "aud":
		    case "loc":
		    case "pos":
		    case "pro":
		    case "voi":
				if ($(tab + "_free").checked)
				{
					$(tab + "_subfields").style.display = "none";
					$(tab + "_upload_area").style.display = "none";
					//UpdateSubtotal(tab, 0);
					UpdateSubtotal(tab, med_free_price);
				}
				else if ($(tab + "_standard").checked)
				{
					$(tab + "_subfields").style.display = "block";
					$(tab + "_upload_area").style.display = "none";
					//UpdateSubtotal(tab, 90);
					UpdateSubtotal(tab, med_standard_price);
				}
				else if ($(tab + "_premium").checked)
				{
					$(tab + "_subfields").style.display = "block";
					$(tab + "_upload_area").style.display = "block";
					//UpdateSubtotal(tab, 250);
					UpdateSubtotal(tab, med_premium_price);
				}
				break;
		}
	}
	else
	{
		UpdateSubtotal(tab, 0);
	}
}

function UpdateSubtotal(tab, price)
{
	for (var i = 0; i < sections.length; i++)
	{
		if (sections[i].code == tab) 
		{
			//alert(sections[i].code + " : " + sections[i].cost + " : + " + parseInt(price));
			sections[i].cost = parseInt(price);
		}
	}
	$(tab + "_subtotal1").innerHTML = "<h3>Subtotal: $" + price + "</h3>";
	$(tab + "_subtotal2").innerHTML = "<h3>Subtotal: $" + price + "</h3>";
	
	UpdateGrandTotal();
}

function UpdateGrandTotal()
{
	var grandtotal = 0;
	for (var i = 0; i < sections.length; i++)
	{
		/*if (sections[i].parent) */grandtotal += parseInt(sections[i].cost);
	}
	//alert("grandtotal: " + grandtotal);
	$("grandtotal").innerHTML = "<h3>Grand Total: $" + grandtotal + "</h3>";
	$("gtotal").value = grandtotal;
}

function ClearAgencyServices(isfull)
{
    ValidateAll();
    if (isfull)
    {
        var serArray = new Array("sales", "interactive", "direct", "brand", "design", "pr", "marketing", "event", "planning");
        for (var i = 0; i < serArray.length; i++)
        {
            $("age_ser_" + serArray[i]).checked = false;
        }
    }
    else
    {
        $("age_ser_full").checked = false;
    }
}

function ServiceClicked()
{
    ValidateAll();
    OptionsChanged("ser");
}

function ValidatePercentages(code, obj)
{
    if (!obj.value.match(/^\d+$/)) 
    {
        obj.value = "";
        return;
    }
    var fields = new Array("cinema", "direct", "events", "internet", "other", "outhome", "printing", "radio", "television");
    
    var total = 0;
    
    for (var i = 0; i < fields.length; i++)
    {
        var value = $F(code + "_mix_" + fields[i]);
        if (value == parseInt(value))
        {
            total += parseInt(value);
        }
        else if (value != "")
        {
            $(code + "_mix_" + fields[i]).value = "";
        }
    }
    if (total > 100)
    {
        obj.value = "";
    }
}


/**** IMAGE UPLOAD ****/
function UploadImage(file)
{
    var target = code + "_clientsandbrands";
	var section = $F(code + "_section_id");
	var action = "GetClients";
	var params = "_a=" + action + "&code=" + code + "&section=" + section;
	
    if (showloading) $(target).innerHTML = load_small;
    Wait(true);
    
	new Ajax.Request(
		url, 
		{method: 'post', 
		parameters: params, 
		onFailure: function(r)
			{
			    Wait(false);
			    $(target).innerHTML = r.responseText;
			},
		onSuccess: function(r)
			{
			    Wait(false);
				$(target).innerHTML = r.responseText;
			}});
}


/**** CLIENTS AND BRANDS ****/
function GetClients(code)
{
	var target = code + "_clientsandbrands";
	var section = $F(code + "_section_id");
	var action = "GetClients";
	var params = "_a=" + action + "&code=" + code + "&section=" + section;
	
	DoAjax(params, target, true);
}
function AddClient(code)
{
    $(code + "_cc_a_ids").value = "";
    $(code + "_client_name_new").value = "";
    GetCategories(code, "c", "a");
    GetCategoryTable(code, "c", "a");
    $(code + "_ccat_a").innerHTML = dropdown_loading;
    $(code + "_csub_a").innerHTML = dropdown_select;
    Element.hide(code + "_clientsandbrands");
    Element.show(code + "_new_client");
}
function EditClient(code, client)
{
    Element.hide(code + "_clientsandbrands");
    Element.show(code + "_edit_client");
    GetClient(code, client);
}
function CancelNewClient(code)
{
    Element.show(code + "_clientsandbrands");
    Element.hide(code + "_new_client");
}
function CancelEditClient(code)
{
    Element.show(code + "_clientsandbrands");
    Element.hide(code + "_edit_client");
}
function AddBrand(code, client)
{
    $(code + "_bc_a_ids").value = "";
    $(code + "_bc_a_client").value = client;
    $(code + "_brand_name_new").value = "";
    GetCategories(code, "b", "a");
    GetCategoryTable(code, "b", "a");
    $(code + "_bcat_a").innerHTML = dropdown_loading;
    $(code + "_bsub_a").innerHTML = dropdown_select;
    Element.hide(code + "_clientsandbrands");
    Element.show(code + "_new_brand");
}
function EditBrand(code, client, brand)
{
    Element.hide(code + "_clientsandbrands");
    Element.show(code + "_edit_brand");
    GetBrand(code, client, brand);
}
function CancelNewBrand(code)
{
    Element.show(code + "_clientsandbrands");
    Element.hide(code + "_new_brand");
}
function CancelEditBrand(code)
{
    Element.show(code + "_clientsandbrands");
    Element.hide(code + "_edit_brand");
}
function GetClient(code, client)
{
	var target = code + "_edit_client";
	var section = $F(code + "_section_id");
	var action = "GetClient";
	var params = "_a=" + action + "&code=" + code + "&section=" + section + "&client=" + client;
	
	$(target).innerHTML = load_small;
    Wait(true);
    
	new Ajax.Request(
		url, 
		{method: 'post', 
		parameters: params, 
		onFailure: function(r)
			{
			    Wait(false);
			    $(target).innerHTML = r.responseText;
			},
		onSuccess: function(r)
			{
			    Wait(false);
				$(target).innerHTML = r.responseText;
				GetCategories(code, "c", "e");
                GetCategoryTable(code, "c", "e");
                $(code + "_ccat_e").innerHTML = dropdown_loading;
                $(code + "_csub_e").innerHTML = dropdown_select;
			}});
}
function GetBrand(code, client, brand)
{
	var target = code + "_edit_brand";
	var section = $F(code + "_section_id");
	var action = "GetBrand";
	var params = "_a=" + action + "&code=" + code + "&section=" + section + "&client=" + escape(client) + "&brand=" + escape(brand);
	
	$(target).innerHTML = load_small;
    Wait(true);
    
	new Ajax.Request(
		url, 
		{method: 'post', 
		parameters: params, 
		onFailure: function(r)
			{
			    Wait(false);
			    $(target).innerHTML = r.responseText;
			},
		onSuccess: function(r)
			{
			    Wait(false);
				$(target).innerHTML = r.responseText;
				GetCategories(code, "b", "e");
                GetCategoryTable(code, "b", "e");
                $(code + "_bcat_e").innerHTML = dropdown_loading;
                $(code + "_bsub_e").innerHTML = dropdown_select;
			}});
}
function SaveNewClient(code)
{
    var target = code + "_clientsandbrands";
	var section = $F(code + "_section_id");
	var role = "";
	for (var i = 1; i < 5; i++)
	{
	    if ($(code + "_client_role" + i + "_new").checked) role += $F(code + "_client_role" + i + "_new") + ";";
	}
	var clientname = $F(code + "_client_name_new");
	var clientcats = $F(code + "_cc_a_ids");
	var action = "SaveClient";
	var params = "_a=" + action + "&code=" + code + "&section=" + section + "&client=&role=" + role + "&clientname=" + escape(clientname) + "&clientcats=" + escape(clientcats);
		
	if (clientname.length < 1) 
	{
	    alert("Please enter a name for this client.");
	    return;
	}
	
	if (clientcats.length < 5) 
	{
	    alert("You need to add at least one category before saving.");
	    return;
	}
	
	DoAjax(params, target, true);
	CancelNewClient(code);
}
function SaveEditClient(code, client)
{
    var target = code + "_clientsandbrands";
	var section = $F(code + "_section_id");
	var role = "";
	for (var i = 1; i < 5; i++)
	{
	    if ($(code + "_client_role" + i + "_edit").checked) role += $F(code + "_client_role" + i + "_edit") + ";";
	}
	var clientname = $F(code + "_client_name_edit");
	var clientcats = $F(code + "_cc_e_ids");
	var action = "SaveClient";
	var params = "_a=" + action + "&code=" + code + "&section=" + section + "&client=" + client + "&role=" + role + "&clientname=" + escape(clientname) + "&clientcats=" + escape(clientcats);
		
	if (clientname.length < 1) 
	{
	    alert("Please enter a name for this client.");
	    return;
	}
	
	if (clientcats.length < 5) 
	{
	    alert("You need to add at least one category before saving.");
	    return;
	}
	
	//alert(params);
	
	DoAjax(params, target, true);
	CancelEditClient(code);
}
function DeleteClient(code, client)
{
    if (confirm("Are you sure you want to remove this client?\r\nDoing so will also delete any brands you have added to the client."))
	{
        var target = code + "_clientsandbrands";
    	var section = $F(code + "_section_id");
    	var action = "DeleteClient";
    	var params = "_a=" + action + "&code=" + code + "&section=" + section + "&client=" + escape(client);
    	
        DoAjax(params, target, false);
        ValidateAll();
    }
}
function DeleteBrand(code, client, brand)
{
    if (confirm("Are you sure you want to remove this brand?"))
	{
        var target = code + "_clientsandbrands";
    	var section = $F(code + "_section_id");
    	var action = "DeleteBrand";
    	var params = "_a=" + action + "&code=" + code + "&section=" + section + "&client=" + escape(client) + "&brand=" + escape(brand);
    	
        DoAjax(params, target, false);
    }
}
function SaveNewBrand(code)
{
    var target = code + "_clientsandbrands";
	var section = $F(code + "_section_id");
	var brandname = $F(code + "_brand_name_new");
	var brandcats = $F(code + "_bc_a_ids");
	var client = $F(code + "_bc_a_client");
	var action = "SaveBrand";
	var params = "_a=" + action + "&code=" + code + "&section=" + section + "&client=" + escape(client) + "&brand=&brandname=" + escape(brandname) + "&brandcats=" + escape(brandcats);
	
	if (brandname.length < 1) 
	{
	    alert("Please enter a name for this brand.");
	    return;
	}
	
	if (brandcats.length < 5) 
	{
	    alert("You need to add at least one category before saving.");
	    return;
	}
	
	DoAjax(params, target, true);
	CancelNewBrand(code);
}
function SaveEditBrand(code)
{
    var target = code + "_clientsandbrands";
	var section = $F(code + "_section_id");
	var brandname = $F(code + "_brand_name_edit");
	var brandcats = $F(code + "_bc_e_ids");
	var brand = $F(code + "_bc_e_brand");
	var action = "SaveBrand";
	var params = "_a=" + action + "&code=" + code + "&section=" + section + "&client=&brand=" + escape(brand) + "&brandname=" + escape(brandname) + "&brandcats=" + escape(brandcats);
	
	if (brandname.length < 1) 
	{
	    alert("Please enter a name for this brand.");
	    return;
	}
	
	if (brandcats.length < 5) 
	{
	    alert("You need to add at least one category before saving.");
	    return;
	}
	
	DoAjax(params, target, true);
	CancelEditBrand(code);
}
function GetCategories(code, type, act)
{
    var target = code + "_" + type + "cat_" + act;
	var action = "GetCategories";
	var params = "_a=" + action + "&code=" + code + "&type=" + type + "&cat_id=&action=" + act;
	
    DoAjax(params, target, false);
}
function GetSubCategories(code, type, act, cat_id)
{
    var target = code + "_" + type + "sub_" + act;
	var action = "GetCategories";
	var params = "_a=" + action + "&code=" + code + "&type=" + type + "&cat_id=" + cat_id + "&action=" + act;
	
	$(target).innerHTML = dropdown_loading;
    DoAjax(params, target, false);
}
function AddCategory(code, type, action)
{
    cat = $(code + "_" + type + "cat_" + action + "_combo");
    sub = $(code + "_" + type + "sub_" + action + "_combo");

    id_obj = $(code + "_" + type + "c_" + action + "_ids");
    
    if (id_obj.value.indexOf(cat.value) > -1 || cat.value.length < 5) 
	{
	    alert("Please select a category and then a sub category.");
	    return;
	}

    if (id_obj.value.indexOf(sub.value) > -1 || sub.value.length < 5) 
	{
	    alert("Please select a sub category.");
	    return;
	}
    
    if (id_obj.value < 5) id_obj.value += sub.value;
    else id_obj.value += ";" + sub.value;
    
    $(code + "_" + type + "cat_" + action + "_combo").selectedIndex = 0;
    $(code + "_" + type + "sub_" + action).innerHTML = dropdown_select;
    
    GetCategoryTable(code, type, action);
}
function GetCategoryTable(code, type, act)
{
    var target = code + "_" + type + "c_" + act + "_table";
    var cats = $F(code + "_" + type + "c_" + act + "_ids");
	var action = "GetCategoryTable";
	var params = "_a=" + action + "&code=" + code + "&type=" + type + "&action=" + act + "&cats=" + cats;
	
    DoAjax(params, target, false);
}
function DeleteCategory(code, type, action, category)
{
    var obj = $(code + "_" + type + "c_" + action + "_ids");
    var ids = $(obj).value;
    $(obj).value = ids.replace(category,"").replace(/;;/,";").replace(/;$/,"").replace(/^;/,"");
    GetCategoryTable(code, type, action);
}




/**** PEOPLE DETAILS ****/
function AddPerson(code)
{
	$(code + "_p_title_add").value = "";
	$(code + "_p_first_add").value = "";
	$(code + "_p_last_add").value = "";
	$(code + "_p_jobtitle_add").value = "";
	$(code + "_p_phone_add").value = "";
	$(code + "_p_fax_add").value = "";
	$(code + "_p_mobile_add").value = "";
	$(code + "_p_email_add").value = "";
	
	Element.show(code + "_addeditperson");
	Element.hide(code + "_p_details");
}
function CancelEditPerson(code)
{
    Element.show(code + "_p_details");
    Element.hide(code + "_editperson");
}
function CancelAddPerson(code)
{
    Element.show(code + "_p_details");
    Element.hide(code + "_addeditperson");
}
function GetPeople(code)
{
	var target = code + "_p";
	var section = $F(code + "_section_id");
	var action = "GetPeople";
	var params = "_a=" + action + "&code=" + code + "&section=" + section;
	//alert(params);
	DoAjax(params, target, true);
}

function EditPerson(code, person)
{
	var target = code + "_editperson";
	var section = $F(code + "_section_id");
	var action = "GetPerson";
	var params = "_a=" + action + "&code=" + code + "&person=" + person + "&section=" + section;
	
	Element.hide(code + "_p_details");
    Element.show(code + "_editperson");
	
	DoAjax(params, target, true);
}

function SaveEditPerson(code, person) //saves edits to an existing person
{
	var target = code + "_p";
	var action = "SavePerson";
	var section = $F(code + "_section_id");
	var title = $F(code + "_p_title_edit");
	var first = $F(code + "_p_first_edit");
	var last = $F(code + "_p_last_edit");
	var jobtitle = $F(code + "_p_jobtitle_edit");
	var phone = $F(code + "_p_phone_edit");
	var fax = $F(code + "_p_fax_edit");
	var mobile = $F(code + "_p_mobile_edit");
	var email = $F(code + "_p_email_edit");
	var modified = $F("modified_by");
	var params = "_a=" + action 
					+ "&code=" + code 
					+ "&section=" + section
					+ "&action=U"
					+ "&person=" + person 
					+ "&title=" + escape(title)
					+ "&first=" + escape(first)
					+ "&last=" + escape(last)
					+ "&jobtitle=" + escape(jobtitle)
					+ "&phone=" + escape(phone)
					+ "&fax=" + escape(fax)
					+ "&mobile=" + escape(mobile)
					+ "&email=" + escape(email)
					+ "&ModifiedBy=" + escape(modified);
	
	if (!email.match(regExEmail) && email.match(regExReq))
	{
	    alert("Please enter a valid email address (or none at all).");
	    return;
	}

	Element.hide(code + "_editperson");	
	DoAjax(params, target, true);
}

function SaveAddPerson(code) //saves a new person
{
	var target = code + "_p";
	var action = "SavePerson";
	var section = $F(code + "_section_id");
	var title = $F(code + "_p_title_add");
	var first = $F(code + "_p_first_add");
	var last = $F(code + "_p_last_add");
	var jobtitle = $F(code + "_p_jobtitle_add");
	var phone = $F(code + "_p_phone_add");
	var fax = $F(code + "_p_fax_add");
	var mobile = $F(code + "_p_mobile_add");
	var email = $F(code + "_p_email_add");
	var params = "_a=" + action 
					+ "&code=" + code 
					+ "&section=" + section
					+ "&action=I"
					+ "&person=" 
					+ "&title=" + escape(title)
					+ "&first=" + escape(first)
					+ "&last=" + escape(last)
					+ "&jobtitle=" + escape(jobtitle)
					+ "&phone=" + escape(phone)
					+ "&fax=" + escape(fax)
					+ "&mobile=" + escape(mobile)
					+ "&email=" + escape(email);
					
	if (!email.match(regExEmail) && email.match(regExReq))
	{
	    alert("Please enter a valid email address (or none at all).");
	    return;
	}
			
    Element.hide(code + "_addeditperson");		
	DoAjax(params, target, true);
}

function DeletePerson(code, person)
{
	if (Element.visible(code + "_editperson")) return;
	
	if (confirm("Are you sure you want to remove this person?"))
	{
		var target = code + "_p";
		var section = $F(code + "_section_id");
		var action = "DeletePerson";
		var params = "_a=" + action + "&code=" + code + "&person=" + person + "&section=" + section;
		
		DoAjax(params, target);
		ValidateAll();
	}
}

function MovePerson(code, person, direction)
{
	if (Element.visible(code + "_editperson")) return;
	
	var target = code + "_p";
	var section = $F(code + "_section_id");
	var action = "MovePerson";
	var params = "_a=" + action + "&code=" + code + "&person=" + person + "&section=" + section + "&direction=" + direction;
	
	DoAjax(params, target);
}


/**** AJAX FUNCTIONS ****/
function DoAjax(params, target, showloading)
{
    if (showloading) $(target).innerHTML = load_small;
    Wait(true);
    
	new Ajax.Request(
		url, 
		{method: 'post', 
		parameters: params, 
		onFailure: function(r)
			{
			    Wait(false);
			    $(target).innerHTML = r.responseText;
			},
		onSuccess: function(r)
			{
			    Wait(false);
				$(target).innerHTML = r.responseText;
				ValidateAll();
			}});
}
function DoAjaxDebug(params, target, showloading)
{
    if (showloading) $(target).innerHTML = load_small;
    Wait(true);
    
	new Ajax.Request(
		url, 
		{method: 'post', 
		parameters: params, 
		onFailure: function(r)
			{
			    Wait(false);
			    $(target).innerHTML = alert(r.responseText);
			},
		onSuccess: function(r)
			{
			    Wait(false);
				$(target).innerHTML = Textify(r.responseText);
			}});
}

function Test()
{
	var target = "testzone";
	var action = "Test";
	var params = "_a=" + action;
	
	$(target).innerHTML = load_small;
	
	new Ajax.Request(
		url, 
		{method: 'post', 
		parameters: params, 
		onFailure: function(r)
			{
			    $(target).innerHTML = "<em>Error: " + r.responseText + "</em>";
			},
		onSuccess: function(r)
			{
				$(target).innerHTML = r.responseText;
			}});
}

