function FormAJAXsubmit(formObj) {
    if (typeof(formObj)=='string') formObj = $(formObj);
    if (typeof(formObj)!='object') return false;
    var tareas = $A(formObj.getElementsByTagName('textarea'));
    tareas.each(function(elem) {
       var inst = tinyMCE.getInstanceById(elem.name);
       if (typeof(inst)=='object') {
           elem.value = inst.getHTML();
       }
    });
    url = formObj.action?formObj.action:document.location.href;
    new Ajax.Request(url, {asynchronous:true, evalScripts:true, parameters:Form.serialize(formObj)});
}


function updateSelect(element, options, selected_value) {
	if (!element) return false;
	if (typeof(element)=='string') element = $(element);
	if (typeof(options)=='string') {
		options = options.split('</option>');
	    for (i=0; i<options.length; i++) {
	    	options[i] = options[i].replace(/<option/g,'');
	    	options[i] = options[i].replace(/\s+value=\'?\"?/g,''); //"'
	    	options[i] = options[i].replace(/(\"|\')/g,''); // '"
	    	options[i] = options[i].split('>');
	    }
	}
	element.options.length = 0;
	for (i=0; i<options.length; i++) {
		if (typeof(options[i][1])=='undefined') continue;
		element.options[element.options.length] = new Option(options[i][1], options[i][0], false, false);
	}
	FieldSetValue(element, selected_value);
}

function FieldSetValue(field, val) {
	if (typeof(field)=='string') field = $(field);
    if (typeof(val)!='undefined') {
        field.value = val; 
    }    
}

function readToggleInput(element, status) {
	if (typeof(element)=='string') element = $(element);
	element.setAttribute('readOnly', typeof(status)!='undefined'?status:true);
	if (typeof(status)=='undefined' || status) {
		element.addClassName('readonly');
	} else {
		element.removeClassName('readonly');
	}
}

function ToggleField(field_id, turn_on) {
    if (!$(field_id)) return;
    $(field_id).disabled=turn_on?false:true; 
    $(field_id).style.background=turn_on?'#fff':'#eee';
}

function reportError(request) {
	alert('Sorry. There was an error.');
}

function openPopupWindow(url, options) {
    window.open (url, "", options); 
}

function searchQuery(element, entry) {
    var queryString = new Array();
    params = element.readAttribute("extraparams")
    if(!params) return entry;
    params.split(',').each(
        function(e){
            e = $(e)
//            alert(e.name + ":" + e.value)
//            if(e.value != "") {
                queryString.push(encodeURIComponent(e.name) + '=' + encodeURIComponent(e.value));
  //          }
        });
    return queryString.join('&');
}

function Autocomplete_size_position(element, update) { 
	if(!update.style.position || update.style.position=='absolute') {
    	update.style.position = 'absolute';
        Position.clone($('searchmodel'), update, {setHeight: false, offsetTop: element.offsetHeight});
    }
    Effect.Appear(update,{duration:0.15});
}


var Application = {
	
	start: function() {
		if($('model-list')) ModelList.activate();
		if($('product_info')) ProductInfo.init();
		if($('map')) Gmap.init();
	}
	
}


Event.observe(window, 'load', function() { Application.start() }, false);

function show_help(srcEl, help_note) {
	if (typeof(srcEl)=='undefined') return false;
	var help_note = $('help_note');
	var help_note_close = $('help_note_close');
	help_note.show();
	help_note_close.show();
	
	Position.clone(srcEl, help_note, {setHeight: false, offsetTop:srcEl.getHeight()});
	Position.clone(help_note, help_note_close, {setHeight: false, setWidth:false, offsetLeft:help_note.getWidth()-help_note_close.getWidth()});
}

function help_close() {
	$('help_note').hide();
	$('help_note_close').hide();
	
}

var Categories = {
	add_edit_flag: 0,
	
	update: function(id, url) {
		if (!Categories.add_edit_flag) {
			if ($('list_item_'+id) && url) {
				new Ajax.Updater('list_item_'+id, url, {asynchronous:true, evalScripts:true});
				Categories.add_edit_flag = 1;
			}
		}
	},
	
	create: function (url) {
		if (!Categories.add_edit_flag) {
			var s = '<tr id="list_item_0"></tr>';
			var el = $('table_list').descendants();
			new Insertion.After(el[1], s);
			new Ajax.Updater('list_item_0', url, {asynchronous:true, evalScripts:true});
			Categories.add_edit_flag = 1;
		}
	},
	
	cancel: function(id, url) {
		if (typeof(id)=='undefined' || !id || url=='') {
			if ($('list_item_0')) $('list_item_0').remove();
		} else {
			new Ajax.Updater('list_item_'+id, url, {asynchronous:true, evalScripts:true});
		}
		Categories.add_edit_flag = 0;
	},
	
	oncreate: function(id) {
		if ($('list_item_0') && id) $('list_item_0').id = 'list_item_'+id;
		Categories.add_edit_flag = 0;
	}
	
}

function url_convert(url) {
	url = url.replace(/^\s*/,'');
	url = url.replace(/\s*$/,'');
	var res_url = escape(url.toLowerCase());
	if (res_url!=url) {
		var pattern = /\%(u[a-zA-Z0-9]{4}|\S{2})/g;
		res_url = res_url.replace(pattern,'_');
	}
	return res_url;
}

var ProductInfo = {

	init : function () {
		ProductInfo.refreshPrice();
		ProductInfo.refreshDiagram();
	},

	refreshPrice : function () {
		if (!$('product_rental_length')) return;
	    var rent_length_index = 1*$F('product_rental_length');
	    var price = 0;
	    if (typeof(prices[rent_length_index])!='undefined') {
	        price += 1*prices[rent_length_index];
	    }
	    if ($('product_option')) {
		    var option_index = 1*$F('product_option');
		    if (typeof(option_prices[option_index])!='undefined') {
		        price += 1*option_prices[option_index];
		    }
	    }
	    $('price').update(currency+price);
	    return true;
	},
	
	refreshDiagram : function () {
		if ($('product_date')) datePickerClosed($('product_date'));
		if ($('order_reserved_date')) datePickerClosed($('order_reserved_date'));
	}

}
var Cart = {
	init: function () {
		
	},
	
	optionChanged: function(itemId, optionId) {
		if (!itemId) return false;
		if (typeof(cart.items[itemId])=='undefined') return false;
		if (typeof(cart.items[itemId].options[optionId])=='object') {
			cart.items[itemId].total = 1*cart.items[itemId].price + 1*cart.items[itemId].options[optionId].price;
			$('item_'+itemId+'_option_price').update('$'+cart.items[itemId].options[optionId].price);
		} else {
			cart.items[itemId].total = cart.items[itemId].price;
			$('item_'+itemId+'_option_price').update('0');
		}
		if (cart.items[itemId].discount_type=='%') {
			var discount = cart.items[itemId].total*cart.items[itemId].discount/100;
		} else {
			var discount = cart.items[itemId].discount;
		}
		cart.items[itemId].total -= 1*discount;
		$('total_'+itemId).update('$'+cart.items[itemId].total);
		var cart_total = 0;
		cart.items.each(function (item) {
			if (typeof(item)=='object' && typeof(item.total)!='undefined') {
				cart_total += 1*item.total;
			}
		});
		$('cart_total').update('$'+cart_total);
		if (typeof(cart.discount)!='undefined' && typeof(cart.discount_type)!='undefined') {
			if (cart.discount_type=='%') {
				var cart_discount = cart_total*cart.discount/100;
			} else {
				var cart_discount = 1*cart.discount;
			}
		} else {
			var cart_discount = 0;
		}
		var payment_total = cart_total - cart_discount;
		$('payment_total').update('$'+payment_total);
	}
	
}

/// Google maps integration
var Gmap = {

	init: function() {
		Gmap.load();
		Gmap.geocoder = new GClientGeocoder();
		Event.observe(window, 'unload', function() { GUnload() }, false);
		if (typeof(gmap_address)!='undefined' && gmap_address!='') {
			Gmap.showAddress(gmap_address);
		}
	},

	load: function() {
	  if (GBrowserIsCompatible()) {
	    Gmap.map = new GMap2($("map"));
	    Gmap.map.addControl(new GSmallMapControl());
		Gmap.map.addControl(new GMapTypeControl());
	    Gmap.map.setCenter(new GLatLng(37.4419, -122.1419), 13);
	  }
	  if ($("map_not_found")) $("map_not_found").hide();
	},

	showAddress: function(address) {
	  Gmap.geocoder.getLatLng(
	    address,
	    function(point) {
	      if (!point) {
	        $("map").hide();
	        $("map_not_found_content").update(address + " not found");
	        $("map_not_found").show();
//	        alert(address + " not found");
	      } else {
	        Gmap.map.setCenter(point, 13);
	        Gmap.marker = new GMarker(point);
	        Gmap.map.addOverlay(marker);
	        Gmap.marker.openInfoWindowHtml(address);
	      }
	    }
	  );
	}

}


var Vendor = {
	update_prepaid_balance: function (url) {
		$('prepaid_balance').update($('waiting_box').innerHTML);
		new Ajax.Updater('prepaid_balance', url, {asynchronous:true, evalScripts:true});
	}

}

