// TODO: Next two variables should be taken from config.configurator.php
var app_width = 980;
var use_accessories_single_select = true;
var combine_stages = false; // combine stages with same name to one stage and show additional stage indicator line with combined stages
var show_substages = true; // show second line with substages, can be disabled (false) only if combine_stages == true

var minimum_cmp_products = 2;

function autoprint()
{
    kill_inputs();
    window.print();
    window.close();
}


    // Check that enough products were selected for comparison (default == 2)
function checkSelectedItems()
{
    if($j('form#compare_form input:checked').length >= minimum_cmp_products)
    {
	return true;
    }
    else
    {
	return false;
    }
}
    function toggleCompareCheckbox(pid)
    {
	$j('#compare_'+pid+':checkbox').attr('checked', !$j('#compare_'+pid).is(':checked'));
	updateCompareButtonStyles();
    }

    function toggleAccessoryCheckbox(pid, req_route, base_params)
    {
	$j('#acc_'+pid+':checkbox').attr('checked', !$j('#acc_'+pid).is(':checked'));
	if($j('#acc_'+pid).is(':checked'))
	{
	    $j('#acc_sel_'+pid).css({'background-color' : '#338FD0'});
	}
	else
	{
	    $j('#acc_sel_'+pid).css({'background-color' : ''});
	}

	if(checkSelectedAccessories())
	{

	}

        if(use_accessories_single_select){
            accessories_select(req_route, base_params);
            document.getElementById('spop').style.visibility='hidden';
        }
    }

    function checkSelectedAccessories()
    {
	if($j('#accessories_selector input:checked').length >= 1)
	{
	    return true;
	}
	else
	{
	    return false;
	}
    }

    function getSelectedAccessories()
    {
	return $j('#accessories_selector input:checked').serializeArray();
    }

    // Enable/disable 'compare selected' buttons depending of number of products selected (checked)
function updateCompareButtonStyles()
{
    if(checkSelectedItems())
    {
    	//check for selected items. changing color mode.

	$j(".cmp_btn").attr("src", get_variable('img_path')+"configurator/compare.gif");

	$j("#t_corner").attr("src", get_variable('img_path')+"configurator/line_corner_T.gif");
	$j("#b_corner").attr("src", get_variable('img_path')+"configurator/line_corner_B.gif");

	$j("#right_zone").removeClass("line1_g").addClass("line1");
    }
    else
    {
    	 //check for selected items. changing color mode.

    	$j(".cmp_btn").attr("src", get_variable('img_path')+"configurator/compare_disable.gif");

    	$j("#t_corner").attr("src", get_variable('img_path')+"configurator/line_corner_T_g.gif");
    	$j("#b_corner").attr("src", get_variable('img_path')+"configurator/line_corner_B_g.gif");


    	$j("#right_zone").removeClass("line1").addClass("line1_g");
    }
}

    // Submit comparison form if enough products were selected
function compareSelectedItems()
{
    if(checkSelectedItems())
    {
	window.open('', 'signaturecompare', 'width=1010,height=750,left='+((screen.width / 2) - 350)+ ',top='+((screen.height / 2) - 250)+',location=no,menubar=no,toolbar=no,scrollbars=1,resizable=1').focus();
	$j('form#compare_form').submit();
    }
}

    // Notify user that configurator session was (auto)saved and s/he can return to it any time until cookies are live
function save()
{
	alert(tg('Current phase in the configurator is now saved.')+'\n'+tg('You will be able to return to the same phase using the \'Restore last session\' button')+'\n'+tg('(that will appear upon your return to the configurator).'));
}


function parse_tr_qty_table()
{
	var str="";
	var str1="";


	if($j(".tr_lim_exceeded").length)
	{
		$j(".tr_lim_exceeded th").each(function(){

		   str1+=$j(this).text() + ", ";
	   	   str1=str1.substr(0,str1.length-2);
		});

			str +=tg('There is a minimun quantity needed for the ');
			str +=" "+str1+" ";
			str += tg('to complete the chosen tank top. It is advised to return to previous stages and re-select the products. Please notice the \"Quantity limitation\" table as a reference.');
			str+=" \n";


		alert(str);
	}

}


// TODO: rename me
// Multi-purpose 'startup' maintenance function
// - Update upper stage indicator with correct stage names
// - Preload images
// - Call auto execute scripts
// - Show/hide copyright depending on the stage (show only in the last stage)
// - Update comparison buttons status (enable/disable)
// - Set onclick event on all the comparison checkboxes to update compare buttons status
function apply_stage_indicator()
{
	var syscolor1 = d('syscolor1').value;
	var syscolor2 = d('syscolor2').value;
	var syscolor3 = d('syscolor3').value;

	var c_s = d('current_stage');
	var t_s = d('total_stages');
	var current_stage = c_s.value * 1; // current stage number
	var total_stages_num = t_s.value * 1; // total stage number

	var snames = d('stage_names');
	if (snames.value) {
		// Commented out : break lines by words
		// var names = snames.value.replace(/ /g,'<br />').split(",");
		var names = snames.value.split(",");
	}

	var surls = d('stage_urls');
	if (surls.value)
		var urls = surls.value.split(",");

	if (current_stage != undefined && total_stages_num != undefined) {
		if (current_stage > total_stages_num) {
			last_stage = 0;
		}

		var total_size = d('stage_indicator').width;
		var segment_size = Math.round(total_size / total_stages_num);

		var complete_size = (segment_size * current_stage);
		var incomplete_size = total_size - (segment_size * current_stage);

		var ind_el = d('stage_indicator');
		var first_line = '';
		var second_line = '';
		var names_new = new Object();

		for(var i = 1; i < total_stages_num; i++)
		{
			if (!(names[i] in names_new))
			{
				names_new[names[i]] = 1;
			}
			else if(names[i] == names[i-1])
			{
				names_new[names[i]] ++;
			}
		}

		for (var h = 1; h <= total_stages_num; h++)
		{
			display_link = false;

			if (h == 1) // The first stage
			{
				progress_bar_class = 'progress_bar_first';
				display_link = true;
			}
			else if (h == total_stages_num) // last stage
			{
				if(current_stage == total_stages_num)
				{
					progress_bar_class = 'progress_bar_last_active';
				}
				else if(h == current_stage + 1)
				{
					progress_bar_class = 'progress_bar_last_after_active';
				}
				else if(current_stage > total_stages_num) // the last stage is over (all stages are completed)
				{
					progress_bar_class = 'progress_bar_last_prev';
					display_link = true;
					parse_tr_qty_table();
				}
				else if (current_stage < total_stages_num)
				{
					progress_bar_class = 'progress_bar_last';
				}
			}
			else if (h < current_stage)  // prev stage
			{
					progress_bar_class = 'progress_bar_prev';
					display_link = true;
			}
			else if (h == current_stage)  // active stage
			{
				progress_bar_class = 'progress_bar_active';
			}
			else if (h == current_stage + 1) // next stage
			{
				progress_bar_class = 'progress_bar_after_active';
			}
			else if (h > current_stage + 1) // all stages after next
			{
				progress_bar_class = 'progress_bar_next';
			}

			if (display_link) {
				content = '<a class="progress_bar_link" style="text-align:center;" href="##" onclick="stepback(\'' + urls[h-1] + '\')">' + names[h-1] + '</a>';
			}
			else {
				content = names[h-1];
			}

			if (h == 1)
			{
				segment_size = 132;
			}
			else
			{
				segment_size = segment_size + 5;
			}

			// Combine stage indicator
			if(names[h-1] != names[h-2])
			{
				var colspan='';
				if(names_new[names[h-1]] > 1)
				{
					colspan = 'colspan="' + names_new[names[h-1]] + '"';
				}

				if(names[h-1] == names[current_stage-1])
				{
					progress_bar_class_1st_line = 'progress_bar_active';
				}
				else
				{
					progress_bar_class_1st_line = progress_bar_class;
				}

				first_line = first_line + '<TD ' + colspan + ' width="' + segment_size + '" class="' + progress_bar_class_1st_line + '" align="center">' + content + '</TD>';
			}
			second_line = second_line + '<TD width="' + segment_size + '" class="' + progress_bar_class + '" align="center">' + content + '</TD>';
		}

		if(combine_stages)
		{
			first_line = '<TR>' + first_line + '</TR>';
		}
		else
		{
			first_line = '';
		}
		second_line = '<TR>'+ second_line+'</TR>';

        var build_table = '<table cellspacing="0" cellpadding="0" style="background-color:' + syscolor2 + '" border=0>' + first_line;
            if(show_substages || !combine_stages) {
                build_table += second_line;
            }
            build_table += '</table>';
            ind_el.innerHTML = build_table;
        }

	// Preload images
	var pl_i = d('preload_images');
	if (pl_i) {
		if (pl_i.value != '') {
			preload_image_object = new Image();
			preload_image_object.onload = function() {
				window.status = ''
			};
			var im_a = pl_i.value.split(',');
			for (z = 0; z < im_a.length; z ++) {
				preload_image_object.src = im_a[z];
				setTimeout(function() {
					window.status = ''
				}, 3000);
				/*alert('preloading image ' + im_a[z]);*/
			}
		}
	}

	// Call auto execute scripts
	var pl_ae = d('auto_execute');
	if (pl_ae) {
		eval(pl_ae.value);
	}

	// Display copyright only on the final stage
	if (current_stage == (total_stages_num + 1)) {
		display_copyright();
	}
	else {
		hide_copyright();
	}

	// Update comparison buttons status
	updateCompareButtonStyles();

	// Set onclick event on all the comparison checkboxes to update compare buttons status
	$j("form#compare_form input:checkbox").click(updateCompareButtonStyles);

	//  update_loginrow();
}

    function apply_ie_image_fix() {
	if (navigator.appName.indexOf("Microsoft")!=-1) {

	    setTimeout(function(){
		var trs = document.getElementsByTagName('img');

		for (i=0;i<trs.length;i++) {
		    if (trs[i].id == 'piclayer') {
			trs[i].style.behavior = 'url(/iepngfix.php)';
		    }
		}
	    },500);
	}
    }

    // Go back to stage specified by backurl parameter
    function stepback(backurl)
    {
	if(backurl == 'home')
	{
	    redirect_wo_warn(window.location.pathname);
	}
	else if (backurl != '')
	{
	    if(backurl.search(/p0/) == -1)
	    {
/*		$j('#l0,#l1').show();*/
		$j('#l1').show();
	    }
	    else
	    {
		$j('#l0,#l1').hide();
	    }

	    xmlreq_put(window.location.pathname+'?act=grp'+backurl,'product_form','apply_stage_indicator()');
	    xmlreq_put(window.location.pathname+'?act=gpd'+backurl,'product_data','apply_ie_image_fix()');
	}
    }

    // Restore
    function restore(restore_url, app, type)
    {
	if(app)
	{
	    // Select Nozzle
	    $j('#app option').removeAttr('selected');
	    $j('option[value='+app+']', $j('#app')).attr({'selected':'selected'});
	    $j('#app_title').removeClass('current_selectbox_title').addClass('selectbox_title');

	    // Select Nozzle Type
	    $j('#l1').load(window.location.pathname + '?app='+app, null, function () {
		if(type)
		{
		    $j('#subapp option').removeAttr('selected');
		    $j('option[value="'+type+'"]', $j('#subapp')).attr({'selected':'selected'});
		    $j('#subtype_title').removeClass('current_selectbox_title').addClass('selectbox_title');
		}
	    });
	}
	$j('#page_content').css({"background":"none"});

	stepback(restore_url);
    }

    // Open last saved configurator session
    function restore_lastsession()
    {
	redirect_wo_warn(window.location.pathname + '?restore=lastsession');
    }

    // Open session indicated by specified url
    function restore_url(url)
    {
	redirect_wo_warn(window.location.pathname + '?restore=url&url=' + url);
    }

    function change_lang_domain(url)
    {
	var redirect_url = url;

	if ($j('#current_stage').val() > 0)
	{
	    redirect_url += '?restore=lastsession';
	}
	redirect_wo_warn(redirect_url);
    }

    function app_select(typeg)
    {
	xmlreq_put(window.location.pathname+'?app='+typeg,'l1');
	$j('#app_title').removeClass('current_selectbox_title').addClass('selectbox_title');
    }


    function subtype_select(subtype)
    {
	//transparent url(/images/style/bg_fix.gif) no-repeat scroll 0 0
	var app_selected = d('app');
	apptype = app_selected.value;
	xmlreq_put(window.location.pathname+'?act=grp1&app1='+apptype+'&fn='+subtype,'product_form','apply_stage_indicator();');
	$j('#subtype_title').removeClass('current_selectbox_title').addClass('selectbox_title');
	$j('#current_stage').val('1');
	apply_stage_indicator();
    }

    function subtype_visual_select(subtype)
    {
	$j('#l1 option[value="'+subtype+'"]').attr('selected', 'selected');
	$j('#l1').show();
	subtype_select(subtype);
    }

    function type_select(grp)
    {
	var app_sel = d('app').value;
	var type_sel = d('subapp').value;
	var sess_save = '&appsel=' + app_sel + '&typesel=' + type_sel;

	xmlreq_put(window.location.pathname+'?act=grp&grp='+grp+sess_save,'product_form','apply_stage_indicator()');
	xmlreq_put(window.location.pathname+'?act=gpd&grp='+grp+sess_save,'product_data','apply_ie_image_fix()');

	d('page_content').style.background="none";
    }

    function compared_product_select(pid)
    {
	window.opener.$j("#selector #p"+pid).click();
	this.close();
    }

    function product_select(req_route, req_procod, req_level, base_params, warning, achtung, deadend)
    {
	$j('#l0,#l1').hide();
	var base_url = '?act=grp&grp='+req_route;
	var base_url2 = '?act=gpd&grp='+req_route;

	var app_sel = d('app').value;
	var type_sel = d('subapp').value;
	var sess_save = '&appsel=' + app_sel + '&typesel=' + type_sel;

	if (deadend != '' && deadend != '*') {
	    alert(deadend);
	    return false;
	}

	if (achtung != '') {
	    alert(achtung);
	}

	var do_it = true;
	if (warning != '') {
	    do_it = confirm (warning);
	}

	if (do_it) {
	    var req_url = window.location.pathname+base_url+base_params+'&p'+req_level+'='+req_procod + sess_save;
	    var req_url2 = window.location.pathname+base_url2+base_params+'&p'+req_level+'='+req_procod + sess_save;
	    xmlreq_put(req_url2,'product_data','apply_ie_image_fix()');
	    xmlreq_put(req_url,'product_form','apply_stage_indicator()');
	   	}
    }

    function accessories_select(req_route, base_params)
    {
	var base_url2 = '?act=gpd&grp='+req_route;

	var app_sel = d('app').value;
	var type_sel = d('subapp').value;
	var sess_save = '&appsel=' + app_sel + '&typesel=' + type_sel;

	var sel_accessories = getSelectedAccessories();
	var accessories = '';
	for (i=0; i<sel_accessories.length; i++)
	{
	    accessories += '&' + $j(sel_accessories[i]).attr('name') + '=' + $j(sel_accessories[i]).attr('name').substring(3);
	}

	var req_url2 = window.location.pathname+base_url2+base_params + sess_save + accessories;
	xmlreq_put(req_url2,'product_data','apply_ie_image_fix()');
    }

function update_loginrow()
{
	xmlreq_put('/html/login_block.php?to=nozzles','loginrow',false);
	// TODO: we need to show login form when user logs out (and not to hide the login row)
	// the code below isn't doing it well, so I'm commenting it
	// hide login row (with logout button) if user was logged out
	/*	$j.ajax({
	    url: "/login.php?check",
	    async: false,
	    cache: false,
	    success: function(resp)
	    {
		resp = resp * 1;
		if(!resp)
		{
		    //		    restore_lastsession();
		    //			$j('#loginrow').hide();
		}
	    }

	});*/
}

function change_bbox_bg(act,pid)
{

	if(act == 1)
	{
	 //check for selected items. changing color mode.
	 if(checkSelectedItems())
	  d("pid_" + pid).style.backgroundImage="url("+get_variable('img_path')+"configurator/line_vertical.gif)";
	 else
	  d("pid_" + pid).style.backgroundImage="url("+get_variable('img_path')+"configurator/line_vertical_g.gif)";


	}
	else
	{
	   d("pid_" + pid).style.backgroundImage="";

	}

	//background-image: url(/images/line_vertical.gif);

	//$line_style1 = "background-image:url(/images/line.1.gif);background-position:316px 50%;";

}


    function selector_filter (req_g) {

	//compare_btn_class
	$j(".compare_btn_class").show();

	//show line background

	// d("right_zone").style.backgroundImage="url(/images/line.1_g.gif)";

	$j("#right_zone").removeClass("line1_nodisplay").addClass("line1_g");

	var frm = d('selector');

	var trs = $j("#selector .bbox");//frm.getElementsByClassName('bbox');

	if (req_g == '0') req_g = '';

	for (i=0;i<trs.length;i++)
	{
	    if (($j(trs[i]).attr('name') == 't'+req_g) || (req_g == ''))
	    {
		trs[i].style.display = '';
		trs[i].style.visibility = '';
	    }
	    else if ($j(trs[i]).attr('name') != 't')
	    {
		trs[i].style.display = 'none';
		trs[i].style.visibility = 'hidden';
	    }
	}
	$j('#type_title').removeClass('current_selectbox_title').addClass('selectbox_title');
	$j('#selector_title').show();
    }




    function show_tech_info (grp,info)
    {
	var info_url = window.location.pathname+'?grp='+grp+'&info='+info;
	var info_url2 = window.location.pathname+'?grp='+grp+'&info='+info+'&view=1';

	/*	document.getElementById('popup_title').innerHTML='Technical Details';
	document.getElementById('spop').style.visibility='visible';
	xmlreq_put(info_url,'popup_content','apply_ie_image_fix()'); */

	window.open(info_url2, 'signaturetech', 'width=750,height=500,left='+((screen.width / 2) - 350)+ ',top='+((screen.height / 2) - 250)+',location=no,menubar=no,toolbar=no,scrollbars=1,resizable=1').focus();
    }

    function show_comment_form_link (url, type) // type can be 'comment' or 'help'
    {
	url = encodeURIComponent(url);
	window.open('nozzles_contact.php?url='+url+'&type='+type, 'nozzle_'+type, 'width=680,height=490,left='+((screen.width / 2) - 350)+ ',top='+((screen.height / 2) - 250)+',location=no,menubar=no,toolbar=no,scrollbars=1,resizable=1').focus();

    }


    function show_download_info (grp)
    {
	var info_url = window.location.pathname+'?grp='+grp+'&download_info=1';

	document.getElementById('popup_title').innerHTML=tg('Download Details');
	document.getElementById('spop').style.visibility='visible';

	xmlreq_put(info_url,'popup_content','apply_ie_image_fix()');

    }

    function open_pdf(path)
    {
//	redirect_wo_warn(path);
	window.open(path, 'nozzle_pdf', 'width=680,height=450,left='+((screen.width / 2) - 350)+ ',top='+((screen.height / 2) - 250)+',location=no,menubar=no,toolbar=no,scrollbars=1,resizable=1').focus();
    }

    function open_accessories(grp, params)
    {
	var info_url = window.location.pathname+'?act=accessories&grp='+grp+params;
	document.getElementById('popup_title').innerHTML=tg('Accessories');
	document.getElementById('spop').style.visibility='visible';
        document.getElementById('popup_content').style.height='400px';

	xmlreq_put(info_url,'popup_content','apply_ie_image_fix()');
    }

    function removeCompareTableCol(col_class)
    {
	if($j('table.compare tr.control td').size() > 2)
	{
	    $j('table.compare tr td.'+col_class).remove();
	    $j('table.compare tr:has(td.col_hidden):last-child').remove();
	    updateCompareTableStyles();
	}
    }

    function updateCompareTableStyles()
    {
	$j('table.compare tr td:nth-child(odd)').removeClass('evencol').addClass('oddcol');
	$j('table.compare tr td:nth-child(even)').removeClass('oddcol').addClass('evencol');
	updateControls();
    }

    function updateControls()
    {
	if($j("table.compare tr.control td").size() <= 2)
	{
	    $j("table.compare tr.control").hide();
	}
    }

    function collapseCompareTableRow(row_class)
    {
	$j('table.compare tr.'+row_class+' td div.expanded, table.compare tr.'+row_class+' th div.expanded').removeClass('shown').addClass('hidden');
	$j('table.compare tr.'+row_class+' td div.collapsed, table.compare tr.'+row_class+' th div.collapsed').removeClass('hidden').addClass('shown');
    }

    function expandCompareTableRow(row_class)
    {
	$j('table.compare tr.'+row_class+' td div.expanded, table.compare tr.'+row_class+' th div.expanded').removeClass('hidden').addClass('shown');
	$j('table.compare tr.'+row_class+' td div.collapsed, table.compare tr.'+row_class+' th div.collapsed').removeClass('shown').addClass('hidden');
    }

    function sortCompareTableByField(sortby, sortord)
    {
	if(sortby)
	{
	    var compare_url = '?sortby=' + sortby;
	    if(sortord)
	    {
		compare_url += '&sortord=' + sortord;
	    }

	    $j('table.compare tr.row'+sortby+' td').each(function(i){
		col_class = $j(this).attr("class");
		if(col_class.slice(0,3).match('col'))
		{
		    var re = new RegExp("col([0-9]+) .*");
		    res = re.exec(col_class);
		    compare_url += '&compare[' + res[1] + ']=on';
		}
	    });

	    window.location.href=window.location.pathname+compare_url;
	}
    }


    function display_copyright()
    {
	$j('td.creditrow div').show();
    }

    function hide_copyright()
    {
	$j('td.creditrow div').hide();
    }

    function redirect_wo_warn(path)
    {
	disable_warn();
	if(path != undefined)
	{
	    window.location.href=path;
	}
    }

    function disable_warn()
    {
	window.onbeforeunload = function () {};
    }

    // copy text from input with id=src to input with id=dest
    // optional parameter indicates, whether to overwrite dest if it is not empty
    function copy_text(src, dest, overwrite)
    {
	if($j('#'+src).val() == $j('#'+dest).val())
	{
	}
	else if(!$j('#'+dest).val() || overwrite)
	{
	    $j('#'+dest).val($j('#'+src).val());
	    copy_overwrite_alert(dest, false);
	    existing_trans_alert(dest, false);
	}
	else
	{
	    copy_overwrite_alert(dest, true);
	}
    }

    function copy_overwrite_alert(dest, show)
    {
	if(show)
	{
	    $j('#copy_'+dest).hide('slow');
	    $j('#overwrite_'+dest).show('slow');
	}
	else
	{
	    $j('#copy_'+dest).show('slow');
	    $j('#overwrite_'+dest).hide('slow');
	}
    }

    function existing_trans_alert(dest, show)
    {
	if(show)
	{
	    $j('#copy_'+dest).hide('slow');
	    $j('#overwrite_'+dest).hide('slow');
	    $j('#existing_'+dest).show('slow');
	    $j('#data_existing_'+dest).text('slow');
	}
	else
	{
	    $j('#copy_'+dest).show('slow');
	    $j('#existing_'+dest).hide('slow');
	}
    }


    //IMAGE HOVER EFFECTS

    $j(document).ready(function (){

                tabs = new Tabs();
                bindEvents();

//		$j(".fbl").mouseover(function(){
//			$j(this).removeClass('fbl').addClass("fbl_hover");
//
//		}).mouseout (function() {
//			$j(this).removeClass('fbl_hover').addClass("fbl");
//		});



		$j("#product_form").mouseover(function(e){
			if($j(e.target).hasClass("fbl_last_frame")){
				$j(e.target).removeClass('fbl_last_frame').addClass('fbl_last_frame_hover');
				return true;
			}
		}).mouseout (function (e){
			if($j(e.target).hasClass("fbl_last_frame_hover")){
				$j(e.target).removeClass('fbl_last_frame_hover').addClass('fbl_last_frame');
				return true;
			}
		});


		$j("#product_form").mouseover(function(e){
			if($j(e.target).hasClass("fbl_last_frame2")){
				$j(e.target).removeClass('fbl_last_frame').addClass('fbl_last_frame2_hover');
				return true;
			}
		}).mouseout (function (e){
			if($j(e.target).hasClass("fbl_last_frame2_hover")){
				$j(e.target).removeClass('fbl_last_frame2_hover').addClass('fbl_last_frame2');
				return true;
			}
		});



		$j(".pic td").mouseenter(function (){

				$j(this).addClass('selected_image');
				$(this)
		}).mouseleave (function (){
				$j(this).removeClass('selected_image');
		}).click(function (){

			compared_product_select($j(this).attr("id"));
		})

	});

        var configurator_string_temp = '';
        function configurator_to_basket(input_str) {
                configurator_string_temp = input_str;
                var pcd = nodeText(d('customer_product_code'));
                if(typeof(pcd) == 'undefined')
                    pcd = '';
                ae_prompt(add_configurator_to_basket_callback_pp, 'Label your product with your custom label:',pcd);
        }
        function add_configurator_to_basket_callback_pp(lbl) {
                var bu = d('basket_url');
                if (bu) var backurl = escape(bu.value);

                var user_flag = '';
                var loc = ''+document.location;
                if (loc.indexOf('u=')!=-1){
                        var ts = loc.substring(loc.indexOf('u='));
                        var dristen = (ts.indexOf('&')!=-1?ts.indexOf('&'):ts.indexOf('#'));
                        user_flag = '&'+ts.substring(0,dristen);
                }
                var new_url = '/order.php?act=addconfigurator&pid='+escape(configurator_string_temp)+'&q=1'+'&lbl='+lbl+user_flag+'&back_url='+backurl+'&bmw='+(app_width-10);
                if (lbl != null) {
                        xmlreq_put(new_url,'basket');
                        scroll_down();
                }
        }

        function openWindow(i_sOpen){
            $j('#popup_title').html(i_sOpen);
            $j('#spop').css('visibility', 'visible');
            $j('#popup_content').css('height', '400px');
            $j('#popup_content').css('width', '800px');
            $j('#popup_content').append($j('#div_'+i_sOpen+' div:first-child'));
            $j('.fbr[value="Close"]').click(function(){
                $j('#div_'+$j('#popup_title').html()).append($j('#popup_content div:first-child'));
            });
            bindEvents();
        }

        function bindEvents(){
            $j(".add_line").click(
                function(){
                    for_name = $j(this).attr('for_module');
                    new_row = $j("tr [name='"+for_name+"']:last").clone(true).insertAfter("tr [name='"+for_name+"']:last");
                    rows_length = $j("tr [name='markup']").length;
                    $j('select', new_row).attr('name', for_name+'_groups['+(rows_length-1)+'][]');
                    $j(this).attr("value", "-");
                    $j(this).unbind("click");
                    $j(this).removeClass("add_line");
                    $j(this).addClass("remove_line");
                    $j(this).click(
                        function(){
                            remove_line($j(this));
                        }
                    );
                }
            );
             $j(".remove_line").click(
                function(){
                    remove_line($j(this));
                }
            );
        }

        function remove_line(obj){
            obj.parent().parent().remove();
        }

        function Tabs(){
            that = this;
            that.lastSelectedTab = null;
            that.partial_submit = true;
            var tabs = $j("td[name^='tab_']");
            // loop all tabs, set onclick function
            tabs.each(function(i, val){
                $j(this).css('cursor', 'pointer');
                $j(this).css('color', '#000');
                $j(this).click(function(){
                    // get tab name without prefix
                    name = $j(this).attr('name').substr(4, $j(this).attr('name').length);
                    // get div of tab
                    content_div = $j('#div_'+name);
                    // disable all fields
                    if(that.partial_submit)
                        that.disableFormFields(content_div);
                    // hide last tab
                    if(that.lastSelectedTab){
                        $j('td[name="tab_'+that.lastSelectedTab+'"]').removeClass('ssft_head');
                        $j('td[name="tab_'+that.lastSelectedTab+'"]').addClass('mmft_head');
                        $j('#div_'+that.lastSelectedTab).css('display', 'none');
                        // disable fields of tab
                        if(that.partial_submit)
                            that.disableFormFields($j('#div_'+that.lastSelectedTab));
                    }
                    // show new tab
                    $j(this).removeClass('mmft_head');
                    $j(this).addClass('ssft_head');
                    content_div.css('display', 'block');
                    // enable tab fields
                    if(that.partial_submit)
                        that.enableFormFields(content_div);
                    // set last selected tab
                    that.lastSelectedTab = name;
                })
            })
            // click first tab on page load
            $j(tabs[0]).trigger('click');
        }

        Tabs.prototype.disableFormFields = function(src_element){
            $j('input', src_element).each(function(){
                $j(this).attr('disabled', 'disabled');
            })
            $j('select', src_element).each(function(){
                $j(this).attr('disabled', 'disabled');
            })
        }

        Tabs.prototype.enableFormFields = function(src_element){
             $j('input', src_element).each(function(){
                $j(this).removeAttr('disabled');
            })
            $j('select', src_element).each(function(){
                $j(this).removeAttr('disabled');
            })
        }


