// JavaScript Document

var global_form = ''
/***** Classes ********/

function aj_request(return_div_ids, url){
	/*Pass strings with '|' as a delimeter*/
	/*Convert passed vars into arrays*/
	var rdi_Array = return_div_ids.split("|");
	var url_Array = url.split("|");
	var rdi_l = rdi_Array.length
	var url_l = url_Array.length
	
	/*Test if same number of values are passed*/
	if(rdi_l !== url_l){
		alert("You haven't passed the same number of URL's to Div Ids'")	
	}
	else{
		for(i=0; i<url_l; i++){
			loader(rdi_Array[i])
			var rand  = parseInt(Math.random()*99999);
			new Ajax.Updater(
				rdi_Array[i],
				url_Array[i]+'?rand='+rand,
				{method:'get', evalScripts:true}
			);	
		}
	}
}
function loader(div_id){
	$(div_id).innerHTML = '<img src="../../pukhr_specific/images/spinner.gif" alt="Loading">'
}

function create_timeout(time, function_name){
	timeout = window.setTimeout(function_name, time)
}
function add_record_blind(ele, input){
	blind(ele)
	$(input).value = ''
}
//submit_frm('child_products_frm', '../../core/aj_insert_form.cfm', 'none')
function submit_frm(form_id, url, exclude){
	blind('working')
	//Form.disable(form_id)
	params = Form.serialize(form_id)
	if(form_id == 'child_products_frm'){
		params = ''
		params = params + 'stock_qty= '+ $('c_stock_qty').value +'&title=' + $('c_title').value + '&' + '_table_name=' + $('c__table_name').value + '&' + 'price=' + $('c_price').value + '&short_difference=' + $('short_difference').value + '&display_sequence=9999' + '&description_dif=' + $('description_dif').value + '&parent_id=' + $('parent_id').value
	}
	var rand  = parseInt(Math.random()*99999);
	url = url + '?rand=' + rand + "&" + params + '&exclude=' + exclude
	global_form = form_id
	if(form_id == 'child_products_frm'){
	//	$('child_products_frm').innerHTML = url
		new Ajax.Request(url, {asynchronous:true, onSuccess:child_submit_frm_complete(form_id)});
	}
	else{
		
		new Ajax.Request(url, {asynchronous:true, onSuccess:submit_frm_complete(form_id)});
	}
}
var puk_prod_title = ''
function submit_frm_complete(form){
	puk_prod_title = $F('title')
	//Form.reset(form)
	create_timeout(1000, "blind('working')")
	create_timeout(1500, "added('"+form+"')")
	
}
function child_submit_frm_complete(form){
	
	create_timeout(1000, "show_children()")	
	Form.reset(form)
	Form.enable(form)
	
}
function show_children(){
	var param = "parent_id="
	var param = param + parseInt($('parent_id_span').innerHTML)
	
	var rand  = parseInt(Math.random()*99999);
	var ajax = new Ajax.Updater(
		
		 'child_products_list',        // DIV id (XXX: doesnt work?)
		 '../child_products/get_child_products.cfm?rand=' + rand,        // URL
		 
		 {                // options
		 method:'get',parameters:param,asynchronous:true,evalScripts:true,onComplete:show_children_complete
			 });
}
function show_children_complete(){
	blind('working')
	if($('child_products_list').style.display == 'none'){
		blind('child_products_list')
	}
	if($('added').style.display == 'none'){
		blind('added')
	}
	if($('child_products').style.display !== 'none'){
		blind('child_products')
	}
}
function insert_record_via_ajax(dbfields, fields, url, successFunction, div_to_hide){
	var dbfields_Array = dbfields.split("|");
	var dbfields_l = dbfields_Array.length
	var fields_Array = fields.split("|");
	var fields_l = fields_Array.length	
	
	var params = ''
	
	for(i=0; i<fields_l; i++){
		var val = $F(fields_Array[i])
		params += '&' + dbfields_Array[i] + '=' + val
	}
	var rand  = parseInt(Math.random()*99999);
	url = url + '?rand=' + rand + params
	new Ajax.Request(url, {asynchronous:true});
	var func = successFunction + "('"+ div_to_hide +"')"
	eval(func)
}
function added(form){
	/*blind('added')
	$('product_name_txt').innerHTML = puk_prod_title
	$('product_name_txt2').innerHTML = puk_prod_title
	*/
	window.location = 'add_complete.cfm'
}
function refresh_window(form){
	blind('added')
	Form.enable(form)
	Form.reset(form)
	$('upload_thumbnail').innerHTML = '<iframe name="hidden_form" id="hidden_form_thumbnail"src="upload_handler.cfm?div_id=thumbnail" height="22" width="400" frameborder="0" scrolling="no"</iframe>'
	$('upload_main').innerHTML = '<iframe name="hidden_form" id="hidden_form_main" src="upload_handler.cfm?div_id=main" height="22" width="400" frameborder="0" scrolling="no"></iframe>'
}
function randomNo(){
	var rand  = parseInt(Math.random()*99999);
	return rand
}
function validate_form(id, form, submit_frm){
	var submit_frm = (submit_frm == null) ? true : submit_frm;
	var id_array = id.split("|");
	var valid = true
	var id_array_l = id_array.length
	for(i=0; i <id_array_l; i++){
		var fld = id_array[i]
		var val = $(fld).value
		if(val == '' || val == null){
			$(fld).style.border = '1px solid red'
			valid = false
		}
		else{
			$(fld).style.border = '1px solid green'
		}
	}
	if(!valid){
		alert('Please fill in required fields')
		return false
	}
	else{
		if(submit_frm){
			$(form).submit()
		}
		else{
			return true
		}
		
	}
}
function check_field(type, id){
	var result = true
	if(type == 'num'){
		lastChar = $F(id).charAt($F(id).length-1)
		if(isNaN(lastChar)){
			if(lastChar != '.'){
				$(id).value = $(id).value.substring(0, $F(id).length-1)
				result = false
				return result
				
			}
			else{
				result = true
				return result	
			}
		}
	}
	else if(type == 'email'){
		if($F(id).length !== 0){
			if($F(id).search('@') == -1){
				alert('This must contain an email address')
				$(id).style.border = '1px solid red'
				return false
			}
			else{
				$(id).style.border = ''
				return true
			}
		}
		else{
			$(id).style.border = ''

			return true
		}
	}
}
function blind(ele){
	Effect.toggle(ele,'slide', {duration:0.3})
}
function create_sort(id){
	Sortable.create(id);
	$(id).addClassName('sortable')
}
function destroy_sort(id){
	poststring = Sortable.serialize(id);
	Sortable.destroy(id);
	$(id).addClassName('none')
	return poststring
}
function highlight(id_of_element){
	new Effect.Highlight(id_of_element);	
}

function trim(inputString) {
   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
   }
   return retValue; // Return the trimmed string back to the user
} // Ends the "trim" function


function working(){
	blind('working')
}

/***** END Classes ********/
//function add_new_product(){
//	refresh_window('products_frm')
//	blind('added')//TODO: change this to be automatically hidden
//}
function child_products(){
	/*
	blind('products_frm_div');
	Effect.toggle('child_products','slide', {duration:1.5});
	blind('tog_product');
	blind('added');
	
	$('product_name_child_title').innerHTML = puk_prod_title
	*/
	var param = ''
	var rand  = parseInt(Math.random()*99999);
	var ajax = new Ajax.Updater(
		
		 'parent_id_span',        // DIV id (XXX: doesnt work?)
		 'get_product_id.cfm?rand=' + rand,        // URL
		 
		 {                // options
		 method:'get',parameters:param,asynchronous:true
			 });
}
function insert_child(){
	//$('parent_id').value = parseInt($('parent_id_span').innerHTML)
	var rand  = parseInt(Math.random()*99999);
	submit_frm('child_products_frm', '../../core/aj_insert_form.cfm', 'none')
}
var puk_tog_prod_open = false
function tog_prod(){
	if(puk_tog_prod_open){
		$('tog_prod_txt').innerHTML = 'Show Product Details'
		blind('products_frm_div');
		puk_tog_prod_open = false
		$('add_product').style.display = ''
		Form.enable('products_frm')
	}
	else{
		$('tog_prod_txt').innerHTML = 'Hide Product Details'
		blind('products_frm_div');
		puk_tog_prod_open = true
		$('add_product').style.display = 'none'
		Form.disable('products_frm')
	}

}
function init(){
	get_supplier_dropdown()
	get_categories_dropdown()
}

function get_supplier_dropdown(){
	aj_request('supplier_dropdown', '../suppliers/aj_supplier_list.cfm')
}

function get_categories_dropdown(){
	aj_request('category_dropdown_adding', '../categories/aj_category_list_add.cfm')
}

function add_category(ele){
	blind(ele)
	$('new_category').value = ''
}
function after_supplier_added(ele){
	loader('supplier_dropdown')
	create_timeout(500, 'get_supplier_dropdown()')
	blind(ele)
}
function after_category_added(ele){
	loader('category_dropdown')
	create_timeout(500, 'get_categories_dropdown()')
	$('new_category').value = ''
	blind(ele)
}
function insert_supplier(ele){
	insert_record_via_ajax(
		'supplier_name', 
		'new_supplier', 
		'../suppliers/aj_add.cfm', 
		'after_supplier_added', 
		ele
	)

}
function insert_category(ele){
	insert_record_via_ajax(
		'title|parent_category_id',
		'new_category|category_id_add', 
		'../categories/aj_add.cfm', 
		'after_category_added', 
		ele
	)
}

function upload_image(){
	if($('upload_file').value !== ''){
		$('upload_image_frm').submit()
	}
	else{
		alert('Select an image to upload')	
	}
}
var product_id = 0
function accept_image(path, div){
	var divPath = "'" + "upload_" + div + "'"
	var add_div = "'" + div + "_add'"
	var add_div_src = '<iframe name="hidden_form" id="hidden_form_'+div+'" src="upload_handler.cfm?div_id='+div+'" height="22"	width="400" frameborder="0" scrolling="no"></iframe>'
	var src = '<input name="" class="text_style_btn" type="button" value="change image" onClick="blind('+add_div+')"><br><div class="form_add_record" id="'+div+'_add" style="display:none;">'+ add_div_src +'</div><img width="150" id="'+div+'_'+path+'" class="uploaded_image" src="../../uploaded_images/' + path + '">'
	$(eval(divPath)).innerHTML = src
	var id = div+"_"+path
	$('image_'+div).value = path
	create_timeout(1000, 'image_changed("'+div+'")')
}
function image_changed(div){
	var new_image = $('image_'+div).value
	//var id = $('id').value
	var param = 'id='+product_id+'&table=products&field=image_'+div+'&value=' + new_image
	var url = 'send_update.cfm?' + param
	new Ajax.Request(url, {asynchronous:true, 
					 onSuccess:image_changed_done()});
}
function image_changed_done(){
	//alert('Image changed')
}
function delete_child(id){
	blind('working')
	new Ajax.Request('../child_products/delete.cfm?id='+id, {asynchronous:true, 
					 onSuccess:done_delete_child()});
}

function done_delete_child(){
	create_timeout(1000, "show_children()")
}

function sort_child_prods(id){
	blind('child_prods_sort')
	var rand  = parseInt(Math.random()*99999);
	var ajax = new Ajax.Updater(
		
		 'change_order_div',        // DIV id (XXX: doesnt work?)
		 '../child_products/change_order.cfm?parent_id='+id+'&rand=' + rand,        // URL
		 
		 {                // options
		 method:'get',asynchronous:true
			 });
	
	create_timeout(1000, "create_sort('child_prods_list')")
	create_timeout(1000, "blind('child_prods_list_table')")
}
function hide_child_sort(){
	destroy_sort('child_prods_list')
	var listArray = poststring.split("&")
	var list = ''
	for(i=0; i<listArray.length; i++){
		var pre_string = 'child_prods_list[]='
		var len = listArray[i].length
		var pre_len = pre_string.length
		if(list == ''){
			list = list + listArray[i].slice(pre_len, len)
		}
		else{
			list = list + ',' + listArray[i].slice(pre_len, len)
		}
	}
	new Ajax.Request('../../core/change_list_order.cfm?table=child_products&list='+list, 
	{asynchronous:true, onSuccess:create_timeout(1000, "complete_child_sort()")
					 });
	//window.location = '../../core/change_list_order.cfm?table=child_products&list='+list
}
function complete_child_sort(){
//	blind('working')
//	blind('child_prods_list_table')
//	create_timeout(1000, "blind('child_prods_sort')")
	var rand  = parseInt(Math.random()*99999);
	var param = "parent_id="
	var param = param + parseInt($('parent_id_span').innerHTML)
	var ajax = new Ajax.Updater(
		
		 'child_products_list',        // DIV id (XXX: doesnt work?)
		 '../child_products/get_child_products.cfm?rand=' + rand,        // URL
		 
		 {                // options
		 method:'get',parameters:param,asynchronous:true,evalScripts:true
			 });
}

/************************** CATEGORIES ************************/

function display_tree(display_id, done){
	var rand  = parseInt(Math.random()*99999);
	var ajax = new Ajax.Updater(
		 display_id, 
		 '../../core/category_tree.cfm?rand=' + rand + '&done=' + done,        // URL
		 
		 {                // options
		 method:'get',asynchronous:true,evalScripts:true
			 });

	if($(display_id).style.display == 'none'){
		create_timeout(1500, "blind('"+display_id+"')")
	}
}
function display_tree_eastbay(display_id, done){
	var rand  = parseInt(Math.random()*99999);
	var ajax = new Ajax.Updater(
		 display_id, 
		 '../../../core/category_tree.cfm?rand=' + rand + '&function=cat_list_estbay&done=' + done,        // URL
		 
		 {                // options
		 method:'get',asynchronous:true,evalScripts:true
			 });

	if($(display_id).style.display == 'none'){
		//create_timeout(500, "blind('"+display_id+"')")
	}
}
function display_tree_adding_product(display_id, done){
	var rand  = parseInt(Math.random()*99999);
	var ajax = new Ajax.Updater(
		 display_id, 
		 '../../core/category_tree.cfm?rand=' + rand + '&function=cat_list&done=' + done,        // URL
		 
		 {                // options
		 method:'get',asynchronous:true,evalScripts:true
			 });

	if($(display_id).style.display == 'none'){
		//create_timeout(500, "blind('"+display_id+"')")
	}
}
function select_from_tree(id){
	$('parent_category_id').value = id
	blind('category_tree')
}
function cat_select(id){
	$('category_id').value = id
	blind('category_tree')
}
var select_for_action_down = false
function select_for_action(id){
	if(select_for_action_down){
		blind('category_actions')
		select_for_action_down = false
	}
	display_actions(id)
}
function display_actions(id){
	
		var rand  = parseInt(Math.random()*99999);
		var ajax = new Ajax.Updater(
		 'category_title',        // DIV id (XXX: doesnt work?)
		 'aj_list_detail.cfm?rand=' + rand + '&id=' + id,        // URL
		 
		 {                // options
		 method:'get',asynchronous:true,evalScripts:true
			 });
		if($('category_actions').style.display == 'none'){
			create_timeout(500, "blind('category_actions')")
		}
}
function change_parent(id){
	alert(id)	
}
function delete_cat(id){
	if(confirm('Are you sure you want to delete this category? \nThis will be permanent and may cause products and other categories to be orphaned'))
	new Ajax.Request('aj_delete.cfm?id='+id, 
	{asynchronous:true, onSuccess:delete_cat_complete
					 });
}
function delete_cat_complete(){
	alert('Category deleted')
	display_tree('category_tree', 'list')
	blind('category_actions')
}

function cat_list(id){
	new Ajax.Request('../categories/aj_get_cat_path.cfm?id='+id, 
	{asynchronous:true, onSuccess:cat_list_complete
					 });
}
function cat_list_estbay(id){
	new Ajax.Request('../../categories/aj_get_cat_path.cfm?id='+id, 
	{asynchronous:true, onSuccess:cat_list_complete
					 });
}
function cat_list_complete(t){
	/*var MyObject = {property1: t};
	DP_Debug.dump(MyObject)*/
	var response_array = t.responseText.split("|");
	var exists = $('selected_category_id_list').value.indexOf(response_array[1])
	if(exists == -1){
		$('selected_category_list').innerHTML = $('selected_category_list').innerHTML + '<p id="cat_'+ response_array[1] +'"><a href="#_" onclick="remove_cat('+ response_array[1] +')">x</a> ' + response_array[0] + '</p>'
		if($('selected_category_id_list').value == ''){
			$('selected_category_id_list').value = $('selected_category_id_list').value + response_array[1]
		}
		else{
			$('selected_category_id_list').value = $('selected_category_id_list').value + ',' + response_array[1]
		}
	}
}
function cat_list_complete(t){
	/*var MyObject = {property1: t};
	DP_Debug.dump(MyObject)*/
	var response_array = t.responseText.split("|");
	var exists = $('selected_category_id_list').value.indexOf(response_array[1])
	if(exists == -1){
		$('selected_category_list').innerHTML = $('selected_category_list').innerHTML + '<p id="cat_'+ response_array[1] +'"><a href="#_" onclick="remove_cat('+ response_array[1] +')">x</a> ' + response_array[0] + '</p>'
		if($('selected_category_id_list').value == ''){
			$('selected_category_id_list').value = $('selected_category_id_list').value + response_array[1]
		}
		else{
			$('selected_category_id_list').value = $('selected_category_id_list').value + ',' + response_array[1]
		}
	}
}
function remove_cat(id){
	Element.remove('cat_'+id)
	var id_array = $('selected_category_id_list').value.split(",");
	var remove_position = (id_array.indexOf(id))
	delete id_array[remove_position]
	$('selected_category_id_list').value = ''
	for(i=0;i<id_array.length;i++){
		if(isNaN(id_array[i])){
		}
		else{
			if($('selected_category_id_list').value == ''){
				$('selected_category_id_list').value = $('selected_category_id_list').value + id_array[i]
			}
			else{
				$('selected_category_id_list').value = $('selected_category_id_list').value + ',' + id_array[i]
			}
		}
	}
}

function show_all_categories(id_list){
	$('selected_category_id_list').value = null
	var id_list = id_list.toString()
	var id_array = id_list.split(",");
	for(i=0;i<id_array.length;i++){
		cat_list(id_array[i])
	}
}
function save_product_categories(id_list, id){
	blind('working')
	new Ajax.Request('save_product_category_list.cfm?id_list=' + id_list + '&id='+id ,
	{asynchronous:true, onSuccess:save_product_categories_complete
					 });
}
function save_product_categories_complete(){
	create_timeout(1500, "blind('working')")
}
/************************** SUPPLIERS ************************/

function load_suppliers(){
	var rand  = parseInt(Math.random()*99999);
		var ajax = new Ajax.Updater(
		 'supplier_list',        // DIV id (XXX: doesnt work?)
		 'aj_supplier_table.cfm?rand=' + rand,        // URL
		 
		 {                // options
		 method:'get',asynchronous:true,evalScripts:true, onSuccess:display_suppliers('supplier_list')
			 });
	
	
}
function display_suppliers(toBlind){
	create_timeout(1500, "blind('"+toBlind+"')")
	create_timeout(2000, "highlight('list_of_suppliers')")
}
function destroy_supplier_sort(){
	blind('supplier_list')
	destroy_sort('list_of_suppliers')
	var listArray = poststring.split("&")
	var list = ''
	for(i=0; i<listArray.length; i++){
		var pre_string = 'list_of_suppliers[]='
		var len = listArray[i].length
		var pre_len = pre_string.length
		if(list == ''){
			list = list + listArray[i].slice(pre_len, len)
		}
		else{
			list = list + ',' + listArray[i].slice(pre_len, len)
		}
	}
	new Ajax.Request('../../core/change_list_order.cfm?table=suppliers&list='+list, 
	{asynchronous:true, onSuccess:display_suppliers('supplier_list')
					 });
}
function supplier_sort_done(){
	create_timeout(1000, "load_suppliers()");
}
function remove_suppler(id){
	if(confirm('Are you sure you want to delete this?\nThis will be permanant')){
		new Ajax.Request('aj_delete_supplier.cfm?id='+id, 
		{asynchronous:true, onSuccess:delete_supplier_done
						 });
	}
}
function delete_supplier_done(id){
	blind('supplier_list')
	create_timeout(500, 'load_suppliers()')
	
}

/************************* PRODUCTS *************************/
function sort_products(){
	$('controls').innerHTML = '<a href="#" onClick="products_sort_done()">Done changing order</a>'
	create_sort('product_list')
}
function products_sort_done(){
	destroy_sort('product_list')
	var listArray = poststring.split("&")
	var list = ''
	for(i=0; i<listArray.length; i++){
		var pre_string = 'product_list[]='
		var len = listArray[i].length
		var pre_len = pre_string.length
		if(list == ''){
			list = list + listArray[i].slice(pre_len, len)
		}
		else{
			list = list + ',' + listArray[i].slice(pre_len, len)
		}
	}
	new Ajax.Request('../../core/change_list_order.cfm?table=products&list='+list, 
	{asynchronous:true, onSuccess:highlight('product_list')
					 });
	$('controls').innerHTML = '<a href="#" onClick="sort_products()">Change order</a>'
}

function delete_product(id){
	if(confirm('Are you sure you want to delete this?\nThis will be permanant')){
		new Ajax.Request('delete_product.cfm?id='+id, 
		{asynchronous:true, onSuccess:delete_product_done(id)
						 });
	}
}
function delete_product_done(id){
	Element.remove( "list_"+ id );
	highlight('product_list')
	
}
function featured(id){
	$('feat_working').display = ''
	var val = $F('featured_product')
	//window.location = '../../core/featured_product.cfm?id='+id+'&val='+val
	new Ajax.Request('../../core/featured_product.cfm?id='+id+'&val='+val, 
		{asynchronous:true, onSuccess:feat_product_done()
						 });
}
function feat_product_done(){
	$('feat_working').display = 'none'
}
function email_signup_check(id, val){
	var valid = check_field('email',id)
	if(valid){
		new Ajax.Request('core/aj_check_account_exists.cfm?email='+val, 
		{asynchronous:true, onSuccess:email_signup_check_done
						 });
	}
}
function email_signup_check_done(t){
	res = t.responseText.indexOf('f')
	if(res !== -1){
		display_status = $('email_account_exists').style.display
		if(display_status !== 'none'){
			blind('email_account_exists')
		}
	}
	else{
		display_status = $('email_account_exists').style.display
		if(display_status == 'none'){
			blind('email_account_exists')
		}
	}
	
}
function go_to_login(){
	window.location = 'login.cfm?email='+$F('Email')
}
var login_url = ''
function login(url){
	if(validate_form('email|password','login_frm',false)){

		login_url = url
		var email = $F('email')
		var password = $F('password')
		new Ajax.Request('log_user_in.cfm?email='+email+'&password='+password, 
			{asynchronous:true, onSuccess:loggedin
							 });
	}
}

function loggedin(t){
	res = t.responseText.indexOf('t')
	if(res !== -1){
		if(login_url == 'account.cfm'){
			window.location = 'account.cfm'
		}
		else if(login_url == 'cart'){
			show_cart()
		}
		else{
			window.location.reload( false )
		}
		
	}
	else{
		//window.location = login_url+'?login=failed'
		blind('login_failed_div')
	}
}
function logout(){
	new Ajax.Request('core/logout.cfm', 
		{asynchronous:true, onSuccess:logout_done
						 });
}
function logout_done(){
	if(confirm('Are you sure you want to logout?')){
		window.location = 'index.cfm'
	}
	
}
/////// Users ////////////
function remove_user(id){
	if(confirm('Are you sure you want to remove this user?\nThis can not be undone')){
		window.location = 'remove_user.cfm?id='+id
	}
}

/////// Aditional Images ////////
function reorder_add_images(ele){
	create_sort(ele)
	var div = "'" + ele + "'"
	$('reorder').innerHTML = '<a href="#" onClick="save_add_images_order('+div+')">Save Order</a>'
}
function save_add_images_order(ele){
	var poststring = destroy_sort(ele)
	var listArray = poststring.split("&")
	var list = ''
	for(i=0; i<listArray.length; i++){
		var pre_string = 'additional_images[]='
		var len = listArray[i].length
		var pre_len = pre_string.length
		if(list == ''){
			list = list + listArray[i].slice(pre_len, len)
		}
		else{
			list = list + ',' + listArray[i].slice(pre_len, len)
		}
	}
	new Ajax.Request('../../core/change_list_order.cfm?table=other_images&list='+list, 
			{asynchronous:true, onSuccess:saved_images_order(ele)
							 });
}
function saved_images_order(ele){
	var div = "'" + ele + "'"
	$('reorder').innerHTML = '<a href="#" onClick="reorder_add_images('+div+')">Reorder</a>'
}

////////TAGS/////////
function filter_tags(tag_filter){
	if(tag_filter !== ''){
		var rand  = parseInt(Math.random()*99999);
		var ajax = new Ajax.Updater(
		'filtered_tags', 
		 'aj_filter_tags.cfm?rand=' + rand + '&tag_filter=' + tag_filter,        // URL
		 
		 {                // options
		 method:'get',asynchronous:true,evalScripts:true
			 });	
	}
	else{
		$('filtered_tags').innerHTML = ''	
	}
}
var g_tag = ''
function add_new_tag(tag){
	g_tag = tag
	new Ajax.Request('aj_how_many_tag_matches.cfm', {parameters:'tag='+tag, onSuccess:tags_counted});		
}
function tags_counted(t){
	if(t.responseText == 0){
		insert_tag(g_tag)
	}
	else{
		var x = Number(t.responseText)
		if(confirm('Are you sure you want to add this tag, there are '+x+' similar tags available')){
			insert_tag(g_tag)
		}
		else{
		}
	}
}
function insert_tag(tag){
	var rand  = parseInt(Math.random()*99999);
		var tag_filter = $F('tag_filter')
		var ajax = new Ajax.Updater(
		'filtered_tags', 
		 'aj_filter_tags.cfm?rand=' + rand + '&new_tag='+ tag + '&tag_filter=' + tag_filter,        // URL
	 
	 {                // options
	 method:'get',asynchronous:true,evalScripts:true
		 });
}
/// Drag and drop
function create_drop_zone(id){
	Droppables.add('tag_drop', {
   accept: 'drag',
   onDrop: function(element) 
     { 
	var id = "'"+element.id+"'"
	var exists = $('tag_drop').innerHTML.indexOf(id)
	if(exists == -1){
		if($('tag_drop').innerHTML == 'Drop Here'){
			$('tag_drop').innerHTML = '<div id="drop_|'+element.id+'">' + element.title+' <a href="#_" onClick="remove_tag('+id+')">X</a></div>';
		}
		else{
			
			$('tag_drop').innerHTML = $('tag_drop').innerHTML + 
			'<div id="drop_|'+element.id+'">' + element.title+' <a href="#_" onClick="remove_tag('+id+')">X</a></div>'; 
		}
		new Effect.Highlight('tag_drop')
		
	}
	else{
		alert('Tag already used')
	}
	
}});
	var rand  = parseInt(Math.random()*99999);
	new Ajax.Updater('tag_drop', 'aj_get_existing_tags.cfm?parent_id='+id+'&rand=' + rand,{method:'get',asynchronous:true});
}

function save_tags(product_id){
	blind('working')
	var tags = $('tag_drop').innerHTML
	/*var listArray = tags.split("</div>")
	for(i=0; i<listArray.length; i++){
		alert(listArray[i])
	}*/
	new Ajax.Request('aj_save_tags.cfm?tags='+escape(tags)+'&product_id='+product_id, {onSuccess:tags_saved});
}
function tags_saved(){
	create_timeout(1500, 'blind("working")')
}
function remove_tag(id){
	Element.remove('drop_|'+id)	
}


/////DOCS//////
function delete_doc(id, product_id){
	if(confirm('Are you sure you want to delete this document?')){
		window.location = 'delete_doc.cfm?id='+id+'&product_id='+product_id
	}
}

