// $Id: form_scripts.js 2727 2007-03-01 15:57:53Z zeke $

var onload_handlers = new Array();
var timeout;

//
// Show/hide any tag by its id.
// parameters:
// id - element id
function fn_show_tag(id, status, stop_listen)
{
	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":"";
		}
	}

	if (stop_listen == true) {
		window.onscroll = '';
	}
}

//
// Select text in text input
//
function fn_select_input(select)
{
	select.select();
}

function addLoadEvent(func) {
 var oldonload = window.onload;
 if (typeof window.onload != 'function') {
   window.onload = func;
 } else {
   window.onload = function() {
     if (oldonload) {
       oldonload();
     }
     func();
   }
 }
}

//
// Disable/enable all form elements inside the tag 
// @id - element id
// @status - boolean (true to disable and false to enable)
function fn_disable_elements(id, status)
{

	node = document.getElementById(id);
	// Process INPUT types...
	inputs = node.getElementsByTagName('INPUT');
	for (i=0;i<inputs.length;i++) {
		node.getElementsByTagName('INPUT')[i].disabled = status;
	}

	// Process TEXTAREA type...
	texts = node.getElementsByTagName('TEXTAREA');
	for (i=0;i<texts.length;i++) {
		node.getElementsByTagName('TEXTAREA')[i].disabled = status;
	}

	// Process SELECT type...
	selects = node.getElementsByTagName('SELECT');
	for (i=0;i<selects.length;i++) {
		node.getElementsByTagName('SELECT')[i].disabled = status;
	}
}

//
// Open pop-up window with detailed image
//
function fn_open_popup_image(popup_script, image_width, image_height)
{
	if (image_width == 0) {
		image_width = 400;
	}
	if (image_height == 0) {
		image_height = 400;
	}
	image_width += 10;
	image_height += 10;

	if ((typeof(handle_popup_image)!='undefined') && (handle_popup_image.closed == false)) {
		handle_popup_image.close();
	}
    handle_popup_image = window.open(popup_script, 'popup_image', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,left=200,top=100,width=' + image_width + ',height=' + image_height + ',resizable=yes');
}

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 mainStr;
}

// 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 / 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 (fn_compare_strings(d_form.elements[i].id, checkbox_id, strict) && !d_form.elements[i].disabled)
			d_form.elements[i].checked = flag;
	}
	return true;
}

// 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)
{
	phone = phone.str_replace(' ', '');
	return fn_is_integer(phone.replace(/[\+\(\)-]/gi, ''));
}

//
// Execute functions on page load
//
function fn_load_handlers()
{
	var i=0;
	for (i=0; i<onload_handlers.length; i++) {
		eval(onload_handlers[i]);
	}

	// If selected_section parameter is passed, add location hash
	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_show_section(id, scts, 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('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_get_window_sizes()
{
	var wnd_arr = new Array();

	if (window.height) {
		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;
	} else {
		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_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_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_ajax_update_vars(page, url, msg)
{
	// 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;
			}
		}
	}

	if (msg.length > 0) {
		window.onscroll = fn_align_element;
		document.getElementById('ajax_message').innerHTML = msg;
		fn_align_element();
		fn_show_tag('ajax_message', false);
		window.setTimeout("fn_show_tag('ajax_message', true, true);", 3000);
	}

	if (typeof(fn_check_all_exceptions) == 'function') {
		fn_check_all_exceptions(false);
	}

	fn_switch_loading_msg(true);
}

function fn_align_element()
{
	var wnd_sizes = fn_get_window_sizes();
	msg = document.getElementById('ajax_message');
	msg.style.top = wnd_sizes['offset_y'] + (wnd_sizes['view_height'] - parseInt(msg.style.height)) / 2;
	msg.style.left = wnd_sizes['offset_x'] + (wnd_sizes['view_width'] - parseInt(msg.style.width)) / 2;
}

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 = fn_format_price(expr, decplaces);
	if(expr.indexOf('.')==0) expr='0'+expr;//ivan sasari fix
	frac_part = expr.substr(expr.indexOf('.')+1) + '0000';
	num = parseInt(expr).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) {
		num += decimals_separator + frac_part.substr(0, decplaces);
	}
	
	return num;
}

function fn_blink(cycle)
{
	if (cycle > 6) {
		be.style.visibility = 'visible';
		clearTimeout(timeout);
		return;
	}
	cycle++;
	if (be = document.getElementById('blinking_elm')) {
		be.style.visibility = (be.style.visibility == 'visible') ? 'hidden' : 'visible';
		timeout = window.setTimeout('fn_blink('+cycle+')', 500);
	}
}

function fn_form_get_request(form_name)
{
	var i = 0;
	var url = index_script + '?';

	if (document.forms[form_name]) {
		elms = document.forms[form_name].elements;
		for (i = 0; i < elms.length ; i++) {
			if (((elms[i].type == 'checkbox' || elms[i].type == 'radio') && elms[i].checked == false) || elms[i].disabled == true) {
				continue;
			}
			url += elms[i].name + '=' + elms[i].value + '&'
		}

		return url;
	}

	return false;
}

function fn_format_price(value, decplaces)
{
	if (typeof(decplaces) == 'undefined') {
		decplaces = 2;
	}

	value = parseFloat(value.toString()) + 0.00000000001;
	return value.toFixed(decplaces);
}

String.prototype.str_replace = function(src, dst)
{

	return this.toString().split(src).join(dst);
}


// isergi

// имеются ли видимые слои (0 - нет, 1 - да)



// Определяем браузер пользователя

isNS4 = (document.layers) ? true : false;
isIE4 = (document.all && !document.getElementById) ? true : false;
isIE5 = (document.all && document.getElementById) ? true : false;
isNS6 = (!document.all && document.getElementById) ? true : false;
isIE7 = (!document.all && document.getElementById) ? true : false;

// Функция, отображающая и скрывающая слои

// Вход:
// objElement - идентификатор(id) слоя;
// bolVisible - булева переменная:
// true  - отобразить слой;
// false - скрыть слой.

// Выход:
// 1


// P.S: В зависимости от типа браузера
// сценарий для манипуляции с видимостью слоёв
// несколько различается.

function switchDiv(objElement,bolVisible){
if(isNS4||isIE4){
     if(!bolVisible) {
       objElement.visibility ="hidden"
     } else {
       objElement.visibility ="visible"
     }     
 } else if (isIE5 || isNS6) {
      if(!bolVisible){
         objElement.style.display = "none";
         
      } else {
        objElement.style.display = "";
        
        }

      }

return 1;
}



// Функция, возвращающая значение указанного ей 
// свойства объекта (не обязательно слоя).

// Вход:
// el    - идентификатор элемента;
// sProp - свойство (left,top...)

// Выход:
// Значение какого-нибудь свойства объекта.



function getPos(el,sProp) {
	var iPos = 0;
	while (el!=null) {
		iPos+=el["offset" + sProp]
		el = el.offsetParent
	}
	return iPos

}



// Функция выдаёт объект с указанным
// ей названием.

// Вход:
// myid - название объекта

// Выход: объект.

function getelementbyid(myid) {
   if (isNS4){
        objElement = document.layers[myid];
     }else if (isIE4) {
        objElement = document.all[myid];
     }else if (isIE5 || isNS6) {
             objElement = document.getElementById(myid);
     }
return(objElement);
}



// Функция отображающая|скрывающая
// слои.
// isergi

// Данная Функция не меняет координаты слоёв,
// не делает их прозрачными, а вызывает функцию movefx,
// которая этим занимается. 


// Вход:
// el - яйчейка таблицы на которой 
// находится указатель;
// m  - наименование слоя, который надо
// отобразить под этой яйчейкой.

function show(el,m) {

if (m!=null) {
m=getelementbyid(m);
}

// получаем элемент в m


        if ((el==null) && (cm)) {
        mstatus=false;
        movefx()
// закрываем меню через movefx

        } else if ((m!=cm) && (m)) {
        if (cm!=null) switchDiv(cm,false);
// пользователь перешёл на другой пункт основного меню
// немедлено сделать невидимым предыдущий (cm) видимый в данный момент слой.  

        switchDiv(m,true); // сделать видимым  слой m
        fxel=el;             
	
        fxm=m;
        fxrect=0; // текущая высота области отсечения (см. ниже)
// 	alert(fxel.offsetWidth);
// 	fxm.Width = fxel.offsetWidth;
        // запоминаем значения в глобальных переменных
        // для использования в дальнейшем

        mstatus=true; // будем открывать меню с помощью movefx
        movefx()
	}
        
        if (m) cm=m; 
        // запоминаем значение m в cm 

  if (tstat==1) {
  clearTimeout(timer1);
  tstat=0
// если таймер timer1 запущен, останавливаем его
  }
 
}


// Функция, "закрывающая" меню.

// Функция принимает на вход b типа boolean
// при true закрывает меню учитывая задержку hide_delay;
// при false (или каком-либо другом значении кроме true) 
// закрывает меню немедленно
 
// и возвращает 1.

function hidemenu(b) {
 if (b)  {
 tstat=1;
 timer1=setTimeout("show(null)",hide_delay);
 } else {
 tstat=0;
 show(null);
 }

}



// Функция, останавливающая таймер, запущенный
// прошлой функцией. Таким образом,
// меню не пропадает.

// Функция ничего не принимает на вход
// и возвращает 1.

function cancelhide() {

if (!mstatus) {
mstatus=1;
// если меню закрывалось, открываем его вновь
}
 
tstat=0;
clearTimeout(timer1);
// останавливаем таймер
 

}



// Функция, отвечающая за эффектное выпадение меню. 
// Ничего не принимает на вход
// Возвращает 1.


function movefx() {
// alert(fxm.offsetHeight);	
if (mstatus) {

fxrect=fxm.offsetHeight;


// Если меню открывается и высота области отсечения больше
// высоты самого слоя, то делаем высоту области равной высоте слоя
// и выходим из функции.
 
} 



if (!mstatus) {
fxrect=0;
switchDiv(fxm,false);
mstatus=true;
cm=null;


// Если меню закрывается и область отсечения меньше 0 
// (признак того, что меню полностью закрылось)
// делаем область = 0
// делаем слой невидимым
// ставим mstatus=true (чтобы при следующем вызове show 
// меню снова открывалось)
// выходим из функции (возвращая 1) 
}

if ((isIE5)||(isIE4)||(isNS4)||(isNS6) || (isIE7)){
	
 if (!isNS4) {
  fxm.style.left = getPos(fxel,"Left") + (0) +"px";
if (mstatus) {
 fxm.style.clip='rect(' + (fxm.offsetHeight-fxrect + 0) + 
' '+ fxm.offsetWidth + ' '+ fxm.offsetHeight +' '+ 0 +')';

  } else {
fxm.style.clip='rect(' + (fxm.offsetHeight-fxrect-10) + 
' '+ fxm.offsetWidth + ' '+ fxm.offsetHeight +' '+ 0 +')';
  }
 
 fxm.style.top = getPos(fxel,"Top")-(6)-If_IE+If_Macintosh+(fxel.offsetHeight-fxm.offsetHeight+fxrect)+"px"; 
 } else {
 fxm.left=getPos(fxel,"Left")+ (0);
 fxm.clip.top=fxm.offsetHeight-fxrect;
 fxm.clip.bottom=fxm.offsetHeight;
 fxm.clip.left=0;
 fxm.clip.right=fxm.offsetWidth;
 fxm.top=getPos(fxel,"Top")+(1)+If_Macintosh+(fxel.offsetHeight-fxm.offsetHeight+fxrect); 

 }

// это всё описано вначале данной статьи :)


} else {
  if (mstatus) {
  fxm.style.left =getPos(fxel,"Left")+"px";
  fxm.style.top = (getPos(fxel,"Top")+ fxel.offsetHeight) +"px";
   } else {
  switchDiv(fxm,false);
  cm=null;
  mstatus=true;
  }

return 1 
}

}


