// $Id: form_scripts.js 2461 2006-11-04 09:51:40Z zeke $

// load htmlarea
// Automatically calculates the editor base path based on the current URL.

//
// Global definitions
//

//
// Show/hide any tag by its id.
// parameters:
// id - element id
// @status - can be true (expand) or false (collapse)
function fn_show_tag(id, status)
{
	if (document.getElementById(id)) {
		if (status == true || status == false) {
			document.getElementById(id).style.display = (status == true)?"none":"";
		} else {
			document.getElementById(id).style.display = (document.getElementById(id).style.display == "")?"none":"";
		}
	}
}

//
// Change section and 
// id - section id

function fn_show_section(id, scts, separate_form, redraw_all)
{

	// Fix bug with changing hash string in opera 8.5+
	if (is_opera && document_loaded == false) {
		onload_handlers.push("fn_show_section('"+id+"', sections ,'"+separate_form+"', "+redraw_all+");");
		return;
	}

	for (i in scts)
	{
		if (i == id) {
			if (document.getElementById('product_save_button')) {
				document.getElementById('product_save_button').style.display = (separate_form == 'Y') ? 'none' : '';
			}
			if (document.getElementById('content_'+i)) {
				document.getElementById('content_'+i).style.display = '';
			}
			document.getElementById('tab_'+i+'_bg').className = 'section-active-tab-bg';
			document.getElementById('tab_'+i+'_left').src = tab_left_active_image_path;
			document.getElementById('tab_'+i+'_right').src = tab_right_active_image_path;
			if (document.getElementsByName('selected_section')) {
				elms = document.getElementsByName('selected_section');
				for (var k=0; k<elms.length; k++) {
					elms[k].value = id;
				}
			}

			location.hash = '#'+id;
		} else {
			if (document.getElementById('tab_'+i+'_bg').className == 'section-active-tab-bg' || redraw_all) {
				if (document.getElementById('content_'+i)) {
					document.getElementById('content_'+i).style.display = 'none';
				}
				document.getElementById('tab_'+i+'_bg').className = 'section-inactive-tab-bg';
				document.getElementById('tab_'+i+'_left').src = tab_left_image_path;
				document.getElementById('tab_'+i+'_right').src = tab_right_image_path;
			}
		}
	}
}

function fn_check_option_type_helper(tag_id, hide)
{
	trs = document.getElementById('variantsglobbo'+tag_id).getElementsByTagName('TR');
	if (trs.length>0) {
		document.getElementById('bulk_'+tag_id).style.display=hide;
		document.getElementById('name_'+tag_id).style.display=hide;
		document.getElementById('position_'+tag_id).style.display=hide;
		document.getElementById('hbulk_'+tag_id).style.display=hide;
		document.getElementById('hname_'+tag_id).style.display=hide;
		document.getElementById('hposition_'+tag_id).style.display=hide;
		for (i=1;i<trs.length;i++) {
			//if (trs[i].id.indexOf('no_hide') == -1) {
				trs[i].style.display=hide;
			//}
		}
	}
}
//
// Check option type
// Parameters:
// @value - can be (S)elect, (R)adio, (I)nput, (T)extarea, (C)heckbox
// @tag_id - tag identifier that should be hided or showed
function fn_check_option_type(value, tag_id)
{
	var i = 0;

	if (document.getElementById(tag_id)) {
		if (value == 'S') {
			document.getElementById('variantsglobbo'+tag_id).parentNode.parentNode.style.display = '';
			fn_check_option_type_helper(tag_id, '');
		}
		if (value == 'R') {
			document.getElementById('variantsglobbo'+tag_id).parentNode.parentNode.style.display = '';
			fn_check_option_type_helper(tag_id, '');
		}
		if (value == 'C') {
			document.getElementById('variantsglobbo'+tag_id).parentNode.parentNode.style.display = '';
			fn_check_option_type_helper(tag_id, 'none');
		}
		if (value == 'I') {
			document.getElementById('variantsglobbo'+tag_id).parentNode.parentNode.style.display = 'none';
		}
		if (value == 'T') {
			document.getElementById('variantsglobbo'+tag_id).parentNode.parentNode.style.display = 'none';
		}
	}
}

// 
// Expand/collapse row
// @tag_id - tag identifier that should be expanded/collapsed
// @flag - can be 1 (expand) or -1 (collapse)
function fn_invert_row(tag_id, flag)
{
	fn_show_tag(tag_id, flag);
	fn_show_tag('plus' + tag_id, flag);
	fn_show_tag('minus' + tag_id, flag);
}

// 
// Expand/collapse all rows in list
// @tag_id - tag identifier of list that should be expanded or collapsed
// @flag - can be 1 (expand) or -1 (collapse)
function fn_invert_all_rows(tag_id, flag)
{
	rows = document.getElementById(tag_id).getElementsByTagName('div');

	for (i = 0; i < rows.length; i++) {
		if (typeof(rows[i].id) != 'undefined' && rows[i].id) {
			fn_show_tag(rows[i].id, flag);
			fn_show_tag('plus' + rows[i].id, !flag);
			fn_show_tag('minus' + rows[i].id, flag);
		}
	}

	fn_show_tag('minus_plus', flag);
	fn_show_tag('plus_minus', !flag);

}


//
// Check / uncheck all checkboxes in form
// @form_name - form name whose checkboxes should be checked or unchecked
// @checkbox_id - tag identifier of checkboxes that should be checked or unchecked
// @flag - can be true or false
function fn_check_all_checkboxes(form_name, flag, checkbox_id, strict)
{
	if (!checkbox_id)
		checkbox_id = 'delete_checkbox';

	if (typeof(strict) == 'undefined') {
		strict = true;
	}

	if(!(d_form = document.forms[form_name]))
		return false;

	for(i=0; i < d_form.length; i++) {
		if (d_form[i].type == 'checkbox' && fn_compare_strings(d_form.elements[i].id, checkbox_id, strict) && !d_form.elements[i].disabled) {
			d_form.elements[i].checked = flag;
		}
	}
	return true;
}

//
// Move selected elements of multiple select input
//
function fn_select_move_elements(from, to)
{

	from_elm = document.getElementById(from);
	to_elm = document.getElementById(to);

	if(!from_elm || !to_elm)
		return false;

	while(to_elm.selectedIndex != -1) {
		from_elm.options[from_elm.options.length] = new Option(to_elm.options[to_elm.selectedIndex].text, to_elm.options[to_elm.selectedIndex].value);
		to_elm.options[to_elm.selectedIndex] = null;
	}

	return true;
}

//
// Select all elements in selects input 
//
function fn_select_save_elements()
{
	var args = fn_select_save_elements.arguments;

	for (i = 0; i < args.length; i++) {
		if (document.getElementById(args[i])) {
			var select = document.getElementById(args[i]);
			for(var k = select.length-1; k >= 0; k--) {
				select.options[k].selected = true;
			}
		}
	}

	return true;
}

//
// Unselect all elements in selects input 
//
function fn_unselect_save_elements()
{
	var args = fn_unselect_save_elements.arguments;

	for (i = 0; i < args.length; i++) {
		if (document.getElementById(args[i])) {
			var select = document.getElementById(args[i]);
			for(var k = select.length-1; k >= 0; k--) {
				select.options[k].selected = false;
			}
		}
	}

	return true;
}


//
// Select text in text input
//
function fn_select_input(select) 
{
	select.select();
}


// Compare 2 strings
// @haystack - where search
// @needle - what search
// @strict - exact compare or partial
function fn_compare_strings(haystack, needle, strict)
{
	if (strict == true) {
		return (haystack == needle);
	} else {
		return (haystack.indexOf(needle) == -1) ? false : true;
	}
}
//
// Check if there are any selected checkboxes in the form
// @form_name - form name in which checkboxes should be selected or deselected
// @checkbox_id - tag id of checkboxes that should be selected or deselected
// @no_alert - do not display notification
// @strict - compare ids strictly or partially
function fn_check_selected(form_name, checkbox_id, no_alert, strict) {
{
	if (typeof(strict) == 'undefined') {
		strict = true;
	}
	
	if (!checkbox_id) {
		checkbox_id = 'delete_checkbox';
	}

	if(!(d_form = document.forms[form_name])) {
		return false;
	}

	for(i=0; i < d_form.length; i++) {
		if (fn_compare_strings(d_form.elements[i].id, checkbox_id, strict)) {
			if (d_form.elements[i].checked) {
				return true;
			}
		}
	}
	if (!no_alert) {
		alert(error_no_items_selected);
	}
	return false;
}																													    }

function fn_delete_selected(form_name, mode_value, no_confirmation, checkbox_id, elm_name, strict) 
{

	if (typeof(strict) == 'undefined') {
		strict = true;
	}
	if (!fn_check_selected(form_name, checkbox_id, '', strict)) {
		return false;
	}
	if (!no_confirmation) {
		if (!confirm(text_delete_confirmation)) {
			return false;
		}
	}

	if (typeof(elm_name)== 'undefined' || elm_name.length == 0) {
		elm_name = mode_name;
	}

	document.forms[form_name].elements[elm_name].value = mode_value;
	document.forms[form_name].submit();
	return true;
}

function fn_load_handlers()
{
	document_loaded = true;
	var i=0;
	for (i=0; i<onload_handlers.length; i++) {
		eval(onload_handlers[i]);
	}

	// If selected_section parameter is passed, add location hash
	if (location.hash.length == 0) {
		var re = new RegExp();
		re.compile("selected_section=\(\\w\)+", "g");
		var m = location.href.match(re);
		if (m) {
			var hash = m[0].split('=');
			location.hash = '#'+hash[1];
		}
	}
}

function fn_escape_url(query) 
{
	var start = query.substr(0, query.indexOf('?'));
	var search = query.substr(query.indexOf('?'));
	if (search) {
		var srch_array = search.split("&");
		var temp_array = new Array();
		for (var i = 0; i < srch_array.length; i++) {
			temp_array = srch_array[i].split("=");
			start += temp_array[0] + '=' + escape(unescape(temp_array[1])) + '&'
		}
	}
	return start;
}

//
// Perform request via <SCRIPT> tag
//
function fn_http_request(script_id, url, show_status)
{
    var agt=navigator.userAgent.toLowerCase();
    var needs_escaping = ((agt.indexOf("msie") != -1) || (agt.indexOf("opera") != -1));

	if (needs_escaping) { 
		url = fn_escape_url(url);
	}

	if (typeof(show_status) == "undefined") {
		show_status = true;
	}

	if (show_status == true){
		fn_switch_loading_msg(false);
	}

	var now = new Date();
	url = url + '&prevent_cache='+now.getTime(); // Prevent script from caching

	var script_tag = document.getElementById(script_id);
	if (script_tag) {
		script_tag.parentNode.removeChild(script_tag);
	}

	script_tag = document.createElement('SCRIPT');
	script_tag.type = 'text/javascript';
	script_tag.language = 'javascript';
	script_tag.id = script_id;
    script_tag.src = url;
	document.body.appendChild(script_tag);
}

//
// String utility functions
//

// extract front part of string prior to searchString
function fn_str_get_front(mainStr,searchStr)
{
	foundOffset = mainStr.indexOf(searchStr)
	if (foundOffset == -1) {
		return null
	}
	
	return mainStr.substring(0,foundOffset)
}

// extract back end of string after searchString
function fn_str_get_end(mainStr,searchStr) 
{
	foundOffset = mainStr.indexOf(searchStr)
	if (foundOffset == -1) {
		return null
	}
	
	return mainStr.substring(foundOffset+searchStr.length,mainStr.length)
}

// insert insertString immediately before searchString
function fn_str_insert_string(mainStr,searchStr,insertStr) 
{
	var front = fn_str_get_front(mainStr,searchStr)
	var end = fn_str_get_end(mainStr,searchStr)

	if (front != null && end != null) {
		return front + insertStr + searchStr + end
	}
	
	return null
}

// remove deleteString
function fn_str_delete_string(mainStr,deleteStr) 
{
	return fn_str_replace_string(mainStr,deleteStr,"");
}

// replace searchString with replaceString
function fn_str_replace_string(mainStr,searchStr,replaceStr) 
{
	var front = fn_str_get_front(mainStr,searchStr)
	var end = fn_str_get_end(mainStr,searchStr)

	if (front != null && end != null) {
		return front + replaceStr + end
	}
	
	return '';
}

function fn_get_window_sizes()
{
	var wnd_arr = new Array();

	if (is_nav) {
		wnd_arr['offset_x'] = self.pageXOffset;
		wnd_arr['offset_y'] = self.pageYOffset;
		wnd_arr['view_height'] = self.innerHeight;
		wnd_arr['view_width'] = self.innerWidth;
		wnd_arr['height'] = window.height;
		wnd_arr['width'] = window.width;
	}
	
	if (is_ie || is_firefox || is_opera8) {
		wnd_arr['offset_x'] = document.body.scrollLeft;
		wnd_arr['offset_y'] = document.body.scrollTop;
		wnd_arr['view_height'] = document.body.clientHeight;
		wnd_arr['view_width'] = document.body.clientWidth;
		wnd_arr['height'] = document.body.scrollHeight;
		wnd_arr['width'] = document.body.scrollWidth;
	}

	return wnd_arr;
}

function fn_str_compare(a, b)
{
  if (a < b) return -1;
  if (a > b) return 1;
  return 0;
}

// Switch elements visibility
function fn_switch_elements(elms_str, exclude_list, hide)
{
	elms_list = elms_str.split(',');
	for (i=0;i<elms_list.length;i++) {
		elms = document.getElementsByTagName(elms_list[i]);
		if (elms.length>0) {
			for (j=0;j<elms.length;j++) {
				if (exclude_list.indexOf(elms[j].name)==-1) {
					elms[j].style.display = (hide == true) ? 'none' : '';
				}
			}
		}
	}
}

function fn_sleep(millis)
{
	date = new Date();
	var curDate = null;
	do { 
		curDate = new Date(); 
	} while(curDate-date < millis);
}




function fn_check_product_feature_type(value, tag_id)
{
	var i = 0;

	if (document.getElementById(tag_id)) {
		if (value == 'S') {
			document.getElementById('box_'+tag_id).style.display = '';
		}
		if (value == 'T' || value == 'C') {
			document.getElementById('box_'+tag_id).style.display = 'none';
		}
	}
}

// Check email address for validity
function fn_check_email(email, msg) {

	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	if (filter.test(email)) {
		return true;
	} else{
		alert(msg);
		return false;
	}
}

//
// This function checks required fields and set a mark if something wrong
//
function fn_check_fields(form_name, extra_ids)
{
	var is_ok = true;
	var seqb_exists = document.getElementById('seqb');
	var error_fields = new Array();

	if (!document.forms[form_name]) {
		return false;
	}
	
	var is_ok = true;
	var set_mark = false;

	elms = document.forms[form_name].elements;
	for (i=0; i<elms.length; i++) {
		set_mark = false;

		// Check the email field
		if (typeof(extra_ids) != 'undefined' && extra_ids[elms[i].id] == 'E') {
			if (fn_check_email(elms[i].value, email_invalid) == false) {
				if (required_fields[elms[i].id] == 'Y' || fn_is_blank(elms[i].value) == false) {
					is_ok = false;
					set_mark = true;
				}
			}
		// Check for integer field
		} else if (typeof(extra_ids) != 'undefined' && extra_ids[elms[i].id] == 'I') {
			if (fn_is_integer(elms[i].value) == false) {
				if (required_fields[elms[i].id] == 'Y' || fn_is_blank(elms[i].value) == false) {
					is_ok = false;
					set_mark = true;
				}
			}
		// Check for phone number
		} else if (typeof(extra_ids) != 'undefined' && extra_ids[elms[i].id] == 'P') {
			if (fn_is_phone(elms[i].value) == false) {
				if (required_fields[elms[i].id] == 'Y' || fn_is_blank(elms[i].value) == false) {
					is_ok = false;
					set_mark = true;
				}
			}
		// Check for blank value
		} else {
			if (required_fields[elms[i].id] == 'Y' && fn_is_blank(elms[i].value) == true) {
				is_ok = false;
				set_mark = true;
				error_fields[elms[i].id] = true;
				if (seqb_exists && document.getElementById('seqb').checked == true && typeof(fn_check_if_shipping) == 'function' && fn_check_if_shipping(elms[i].id)) {
					document.getElementById('seqb').click();
				}
			}
		}
		if (document.getElementById('status_'+elms[i].id)) {
			document.getElementById('status_'+elms[i].id).innerHTML = (set_mark == true)? warning_mark : "&nbsp;";
		}
	}

	if (is_ok == false) {
		alert(message);
	}
	return is_ok;
}

//
// Checks if the value is blank
//
function fn_is_blank(val){
	if (val==null){
		return true;
	}
	for (var i=0; i<val.length; i++) {
		if((val.charAt(i)!="\t")&&(val.charAt(i)!="\n")&&(val.charAt(i)!="\r")){
			return false;
		}
	}
	return true;
}

//
// Checks if the value is integer
//
function fn_is_integer(val)
{
	if(fn_is_blank(val)){
		return false;
	}
	for(var i=0; i<val.length; i++){
		if (!fn_is_digit(val.charAt(i))) {
			return false;
		}
	}
	return true;
}

//
// Checks if the value is digit
//
function fn_is_digit(num)
{
	if(num.length>1){
		return false;
	}
	var string="1234567890";
	if (string.indexOf(num)!=-1){
		return true;
	}
	return false;
}

//
// Checks if the value is phone number
//
function fn_is_phone(phone)
{
	return phone.match(/^\(?\d{3}\)?[ ]?[\d-]*$/gi) ? true : false;
}


function fn_display_trigger()
{
	var elms = document.getElementsByTagName('SPAN');
	var args = fn_display_trigger.arguments;

	for (i=0;i<elms.length;i++) {
		for (j=0;j<args.length;j++)	{
			if (elms[i].id.indexOf(args[j]) == 0) {
				elms[i].style.display = (elms[i].style.display == 'none') ? '' : 'none';
			}
		}
	}
}

function fn_switch_loading_msg(status)
{
	var dlg = document.getElementById('dialog_bg');
	var msg = document.getElementById('dialog_msg');

	var wnd_sizes = fn_get_window_sizes();
	dlg.style.left = 0;
	dlg.style.top = 0;
	dlg.style.width=wnd_sizes['width'];
	dlg.style.height=wnd_sizes['height'];

	msg.style.left = wnd_sizes['offset_x'];
	msg.style.top = wnd_sizes['offset_y'];
	msg.style.width = wnd_sizes['view_width'];
	msg.style.height = wnd_sizes['view_height'];

	fn_show_tag('dialog_bg', status);
}

function fn_ajax_update_vars(page, url)
{
	// Set page input field to current page
	if (page.length > 0) {
		elms = document.getElementsByName('page');
		if (elms.length>0) {
			for (var i=0; i<elms.length; i++) {
				elms[i].value=page;
			}
		}
	}

	if (url.length > 0) {
		elms = document.getElementsByName('redirect_url');
		if (elms.length>0) {
			for (var i=0; i<elms.length; i++) {
				elms[i].value=url;
			}
		}
	}

	fn_switch_loading_msg(true);
}

function fn_hotkeys(evt)
{
	var char_code = (evt.which) ? evt.which : event.keyCode;

	// CTRL + ' - show search by pid window
	if (evt.ctrlKey && char_code == 222) {
		if (result = prompt('Product ID', '')) {
			window.location=index_script+'?'+target_name+'=products&'+mode_name+'=update&product_id='+result;
		}
	}
}

function fn_format_num(expr, decplaces, primary)
{
	var num = '';
	var decimals = '';
	var tmp = 0;
	var k = 0;
	var i = 0;
	var thousands_separator = (primary == true) ? primary_thousands_separator : secondary_thousands_separator;
	var decimals_separator = (primary == true) ? primary_decimals_separator : secondary_decimals_separator;

	expr = expr.toString();
	tmp = parseInt(expr);
	num = tmp.toString();

	// Separate thousands
	if (num.length >= 4 && thousands_separator != '') {
		tmp = new Array();
		for (var i=num.length-3; i>-4 ; i=i-3) {
			k = 3;
			if (i<0) {
				k = 3 + i;
				i=0;
			}
			tmp.push(num.substr(i,k));
			if (i==0) {
				break;
			}
		}
		num = tmp.reverse().join(thousands_separator);
	}

	// Add decimals
	if (decplaces > 0) {
		if (decimals_separator!= '' && expr.indexOf('.') != -1) {
			decimals = expr.substr(expr.indexOf('.')+1, decplaces);
		} else {
			decimals = '0';
		}

		if (decimals.length < decplaces) {
			tmp = decimals.length;
			for (i=0; i<decplaces-tmp; i++) {
				decimals += '0';
			}
		}
		num += decimals_separator + decimals;
	}
	
	return num;
}
