// JavaScript Document
var debug = false;	//whether you want to see the results of the javascript in alerts

//global response from ajax_product_form.php
var globalResponse="";

crir.addEvent(window, 'load', submitForm, false);
var loaded_attribute_filters = false;	//whether attribute filters have been loaded yet

function delayForm()
{
	setTimeout(submitForm, 5);
}

function submitForm()
{
	sendRequest(document.generalForm);
}

function sendRequest(objForm, background_loading)
{
	if (background_loading != "Y")
		document.getElementById('show').innerHTML = "<img src='/images/loading_chess.gif' style='padding:20px;' />"
	
	var vars = 'task=ajax_update';
	var regexp = RegExp(/[^0-9]/gi);	//regular expression
	var tmp="";
	
	try
	{
		for (var i=0; i<objForm.elements.length; i++)
		{
			if (objForm.elements[i].name)
			{	
				if (objForm.elements[i].type!="checkbox" || objForm.elements[i].checked)
				{
					vars += '&'+objForm.elements[i].name+'='+objForm.elements[i].value;
				}
				else
				{
					vars += '&'+objForm.elements[i].name+'=N';
				}
				if (objForm.elements[i].type=="checkbox" && background_loading!="Y")
				{
					objForm.elements[i].checked = false;
					objForm.elements[i].disabled = true;
					document.getElementById("label_for_"+objForm.elements[i].id).className = "checkbox_disabled";
				}
			}
		}
	}
	catch (e)
	{
		//nothing
	}
	
	if (background_loading != "Y")
	{
		new Ajax.Request("/inc/ajax_product_form.php", 
			{ 
			method: 'post', 
			postBody: vars,
			onComplete: showResponse 
			});
	}
	else
	{
		new Ajax.Request("/inc/ajax_product_form_background.php", 
			{ 
			method: 'post', 
			postBody: vars,
			onComplete: showBackgroundResponse 
			});
	}
	//return false;	//this is needed so page doesn't refresh
}

function showResponse(req)
{
	if (req.responseText.indexOf("***RELOAD_PAGE***") != -1)
	{
		window.location.reload();
		return;
	}
	//split up the response by *@@@* as noted in ajax_product_form.php 
	globalResponse = req.responseText.split('*@@@*');
	//alert(globalResponse);
	if (globalResponse.length > 1)
		updateFilterables();
	document.getElementById('show').innerHTML = req.responseText;
}

function showBackgroundResponse(req)
{
	//split up the response by *@@@* as noted in ajax_product_form.php 
	globalResponse = req.responseText.split('*@@@*');
	//alert(globalResponse);
	
	var str = "ATTRIBUTE INFO:\n\n";
	var attribute_response = req.responseText.split('*###*');
	var attribute_url_name = "";
	
	if (attribute_response.length > 1 && !loaded_attribute_filters)
	{
		var attribute_info = attribute_response[1].split("*$$$*");
		if (attribute_info.length > 1)
		{
			for (var i=0; i<attribute_info.length; i++)
			{
				if (i%2==0)
				{
					attribute_url_name = attribute_info[i];
					str += attribute_info[i]+"\n\t";
				}
				else
				{
					if (attribute_url_name != "")
					{
						var this_attribute = attribute_info[i].split("*!!!*");
						var this_output = "";
						if (this_attribute.length > 0)
						{
							for (var j=0; j<this_attribute.length; j++)
							{
								var newli = document.createElement("li");
								var newinput = document.createElement("input");
								var this_id = makeUrlName(this_attribute[j]);	//name is makeUrlName'd to protect special characters
								
								try
								{
									var already_there = document.getElementById("filter~attribute~"+attribute_url_name+"~"+this_id);
									if (already_there != null)
										continue;
								}
								catch (e)
								{
									
								}
								
								newinput.setAttribute("type","checkbox");
								newinput.setAttribute("value","Y");	//the value when checked	
								newinput.setAttribute("name","filter~attribute~"+attribute_url_name+"~"+this_id);
								newinput.setAttribute("id","filter~attribute~"+attribute_url_name+"~"+this_id);
								newinput.setAttribute("class","custom_input");
								
								var newlabel = document.createElement("label");
								newlabel.setAttribute("id","label_for_filter~attribute~"+attribute_url_name+"~"+this_id);
								newlabel.setAttribute("for","filter~attribute~"+attribute_url_name+"~"+this_id);
								
								var newtext = document.createTextNode(this_attribute[j]);
								newlabel.appendChild(newtext);
								
								newli.appendChild(newinput);
								newli.appendChild(newlabel);
								
								document.getElementById(attribute_url_name+"_ul").appendChild(newli);
							}
						}
						else
						{
							var newli = document.createElement("li");
							var newtext = document.createTextNode("n/a");
							newli.appendChild(newtext);
							
							document.getElementById(attribute_url_name+"_ul").appendChild(newli);
						}
						try
						{
							var todel = document.getElementById(attribute_url_name+"_hidden");
							todel.parentNode.removeChild(todel);	//since this was just needed to get the inital attribute values
						}
						catch(e)
						{
							//do nothing
						}
					}
					str += attribute_info[i].split("*!!!*")+"\n\n";
					//reapply styles loaded from custom_input onload now
					crir.init();
					loaded_attribute_filters = true;
				}
			}
		}
	}
	
	if (debug)
		alert(str);
	
	if (globalResponse.length > 1)
		updateFilterables("Y");
}

function updateFilterables(is_background)
{
	var to_enable, i, paging;
	
	if (debug)
	{
		alert("Fields to enable:\n"+globalResponse[1]+"\n\nFields to check:\n"+globalResponse[2]);
	}
	try
	{
		if (globalResponse[1]!="")	//to enable
		{
			to_enable = globalResponse[1].split(",");
			for (i=0; i<to_enable.length; i++)
			{
				document.getElementById(to_enable[i]).disabled = false;
				document.getElementById("label_for_"+to_enable[i]).className = "checkbox_unchecked";
			}
			
			//things are already disabled that need to be, so we don't have to do anything with them
		}
		
		if (globalResponse[2]!="")	//to check
		{
			to_check = globalResponse[2].split(",");
			for (i=0; i<to_check.length; i++)
			{
				document.getElementById(to_check[i]).disabled = false;
				document.getElementById(to_check[i]).checked = true;
				document.getElementById("label_for_"+to_check[i]).className = "checkbox_checked";
			}
		}
	}
	catch (e)
	{
		//alert(e+"\nProblem with: "+to_enable[i]);
	}
	
	//show paging (Page X of Y)
	document.getElementById("paging").innerHTML = "Page "+globalResponse[3]+" of "+globalResponse[4];
	document.getElementById("paging2").innerHTML = "Page "+globalResponse[3]+" of "+globalResponse[4];
	document.getElementById("cur_page").value = globalResponse[3];
	
	//only run the background response if no filters were checked and this isn't already the background response
	if (is_background != "Y")// && globalResponse[2]=="")
		sendRequest(document.generalForm, "Y")
}

function showAttributeValues(attribute_url_name)
{
	document.getElementById(attribute_url_name+"_holder").style.display = "none";
	document.getElementById(attribute_url_name+"_holder2").style.display = "";
}

function clearAll()
{
	var objForm = document.generalForm;
	for (var i=0; i<objForm.elements.length; i++)
	{
		if (objForm.elements[i].name)
		{	
			if (objForm.elements[i].type=="checkbox")
			{
				objForm.elements[i].checked = false;
				objForm.elements[i].disabled = false;
				document.getElementById("label_for_"+objForm.elements[i].id).className = "checkbox_unchecked";
			}
		}
	}
	document.getElementById('cur_page').value = 1;
	sendRequest(objForm);
}

function navigate(direction)
{
	if (direction == "first")
	{
		document.getElementById('cur_page').value = 1;
	}
	else if (direction == "previous")
	{
		document.getElementById('cur_page').value = Math.max(1, parseInt(document.getElementById('cur_page').value)-1);
	}
	else if (direction == "next")
	{
		document.getElementById('cur_page').value = Math.min(1000, parseInt(document.getElementById('cur_page').value)+1);
	}
	else if (direction == "last")
	{
		document.getElementById('cur_page').value = 1000;	//hopefully there are never more than 1000 pages - sheesh.
	}
	submitForm();
}

function changeBar(key, obj)
{
	document.generalForm.elements[key].value = obj.value;
	submitForm();
}


function makeUrlName(old)
{
	var str = old;
	str = str_replace("&","and",trim((str+'').toLowerCase()));
	str = str_replace("#","num",str);
	str = str_replace("+","_",str);
	str = str_replace(" - ","_to_",str);
	str = str.replace(/[\/]/g, "_");
	str = str_replace(" ","_",str);
	str = str.replace(/[^A-Za-z0-9Ρρ_.]/g, "");
	str = str_replace("__","_",str);
	str = str_replace("-","_",str);
	//str = str.replace(/\.$/g, "_");
	return str;
}

function str_replace(srch, rplce, subject)
{
    var s = subject;
    var ra = r instanceof Array, sa = s instanceof Array;
    var f = [].concat(srch);
    var r = [].concat(rplce);
    var i = (s = [].concat(s)).length;
    var j = 0;
    
    while (j = 0, i--) {
        if (s[i]) {
            while (s[i] = (s[i]+'').split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
        }
    }
 
    return sa ? s : s[0];
}

function trim(str, chars)
{
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}