// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

// toggle display of a <div> with two different buttons for show/hide
function toggle_div_with_button(div_name, button_show, button_hide, button_id) {
	visible = $(div_name).style.display;
	if (visible == 'none') {
		$(div_name).style.display="inline"
		$(button_id).innerHTML = button_hide;
	} else {
		$(div_name).style.display="none"
		$(button_id).innerHTML = button_show;
	}
} 

// offer handling ==============================================
function offers_init_page(upd_error, continue_edit){
    if (upd_error || continue_edit) 
        offers_toggle_edit();
    else 
        offers_toggle_display();
}

function offers_toggle_edit(){
    $('display_div').hide();
    $('edit_div').show();
}

function offers_toggle_display(){
    $('display_div').show();
    $('edit_div').hide();
}

// toggles the display of a div element depending on the value of a checkbox
function toggle_display_div_on_checked(div_id, element){
	//alert ('element ' + element.id + "value= " + element.checked);
	if (element.checked) $(div_id).show(); else $(div_id).hide();
    //$(div_id).toggle();
}

function remove_price_row(element, new_record_flag){
    // important: call must be with $(this), otherwise IE can't use prototype extensions
    // new records can be deleted from the table,
    // existing records must be flagged for delete
    if (new_record_flag) {
        element.up('.price_row').remove();
    }
    else {
        $(element).next('.should_destroy').value = 1
        $(element).up('.price_row').hide();
    }
}

function remove_category_selections(level){
    // remove all selections with higher levels
    element = $('offer_category_select_div');
    last_cat = $(element).down('.cat_group', level - 1);
    next_cat = last_cat.next('.cat_group');
    while (typeof(next_cat) != 'undefined') {
        next_cat.remove();
        next_cat = last_cat.next('.cat_group');
    }
}

function upd_assigned_categories(element_id, level, category){
    // maintain the array with the selected categories in form-element
    var cat = $(element_id);
    var cat_value = cat.value.split('-');
    var cat_level = level - 1;
    
    // update the current level
    cat_value[cat_level] = category;
    
    // build a new string for the form
    var cat_new = "";
    for (i = 0; i < cat_value.length; i++) {
        if (i <= cat_level) {
            cat_new = cat_new + cat_value[i] + "-";
        }
    }
    cat.value = cat_new;
}

// convert the url's to absolute adresses
function groupidoImageURLConverter(url, node, on_save) {
	// convert the relative image URL to an absolute URL
	// this is especially needed for firefox
	var new_url = url;
	if (typeof(node) == 'string' && node.toLowerCase() == 'img') {
		var editor = tinyMCE.activeEditor;
		new_url = editor.documentBaseURI.toAbsolute(url);
		//alert ("on_save=" + on_save + " url=" + url + " node=" + node);		
	}
	// Return new URL
	//alert ("new_url " + new_url);
	return new_url;
}


function groupidoPasteWordContent (type, content) {
	switch (type) {
		// Gets executed before the built in logic performes it's cleanups
		case "before":
			content = groupidoPasteWordContentBefore(content);
			break;

		// Gets executed after the built in logic performes it's cleanups
		case "after":
			content = groupidoPasteWordContentAfter(content);
			break;
	}
	
	return content;
}

function groupidoPasteWordContentBefore(content) {
	//alert ("groupidoPasteWordContentBefore, content=" + content);
	
	new_html = content;
	//alert ("start before with html " + new_html);
	
	return new_html;
}

function groupidoPasteWordContentAfter(content) {
	//alert ("groupidoPasteWordContentAfter, content=" + content);
	
	html = content;
	
	// remove the links resulting from table of contents
	new_html = '';
	from = 0;
	anchors = /(<a name="?_toc){1}(.*?)>{1}([\S\s]*?)(<\/a>){1}/img;
	//alert ("start after with html " + html);
	while ((result = anchors.exec(html)) != null) {
		//alert ("Matched at position " + result.index + " until " + anchors.lastIndex + 
		//	"\n>" + result[0]  + "<" 
		//	+ "\nr1= " + result[1]
		//	+ "\nr2= " + result[2]
		//	+ "\nr3= " + result[3]
		//	+ "\nr4= " + result[4]
		//	+ "\nr5= " + result[5]); 
		new_html = new_html + html.substring(from, result.index) + result[3];
		from = anchors.lastIndex;
		//alert ("new_html=" + new_html);
	}
	// get the last part of the string
	new_html = new_html + html.substring(from, html.length);
	//alert ("new_html=" + new_html);
	
	// replace all bullets before a header text
	var bull = String.fromCharCode(8226);
	for (var i=1; i<=6;i++){
		new_html = new_html.replace(new RegExp("<h"+ i + ">" + bull, "gi"), "<h" + i + ">");
	}

	//alert ("new_html=" + new_html);
	return new_html;
}

function groupidoCleanupCallback(type, value) {
	//alert ("groupidoCleanupCallback, type=" + type + " , value=" + value);
	switch (type) {
		case "get_from_editor":
			//alert("before Value HTML string: " + value);
			value = groupidoCleanupExtension(value);
			//alert("after Value HTML string: " + value);
			break;
		case "insert_to_editor":
			//alert("before Value HTML string: " + value);
			value = groupidoCleanupExtension(value);
			//alert("after Value HTML string: " + value);
			break;
		case "submit_content":
			break;
		case "get_from_editor_dom":
			break;
		case "insert_to_editor_dom":
			break;
		case "setup_content_dom":
			break;
		case "submit_content_dom":
			break;
	}

	return value;
}

function groupidoCleanupExtension(content) {
	html = content;
	//alert (html);

	// replace HTML substitution characters
	html = html.replace(/&lt;/g, ' <');
	html = html.replace(/&gt;/g, '> ');

	// remove all comments which will be produced when pasting from a word document
	var result;
	var new_html = "";
	var from = 0;
	var comments = /(<!--){1}[\S\s]*?(-->){1}/gm;
	while ((result = comments.exec(html)) != null) {
		//alert ("Matched " + " at position " + result.index + 
		//		" ;next search starts at " + comments.lastIndex + ">" + result[0] + "<" );
		new_html = new_html + html.substring(from, result.index);
		from = comments.lastIndex;
	}
	// get the last part of the string
	new_html = new_html + html.substring(from, html.length);
	//alert ("new after first run >>" + new_html + "<<");

	// second run to remove the links resulting from table of contents
	html = new_html;
	new_html = '';
	from = 0;
	anchors = /(<a name=){1}(.*?)>{1}([\S\s]*?)(<\/a>){1}/mg;
	//alert ("start with html " + html);
	while ((result = anchors.exec(html)) != null) {
		//alert ("Matched at position " + result.index + " until " + anchors.lastIndex + 
		//	"\n>" + result[0]  + "<" 
		//	+ "\nr1= " + result[1]
		//	+ "\nr2= " + result[2]
		//	+ "\nr3= " + result[3]
		//	+ "\nr4= " + result[4]
		//	+ "\nr5= " + result[5]); 
		new_html = new_html + html.substring(from, result.index) + result[3];
		from = anchors.lastIndex;
		//alert ("new_html=" + new_html);
	}
	// get the last part of the string
	new_html = new_html + html.substring(from, html.length);
	//alert ("new after second run >>" + new_html + "<<");
	
	// replace all bullets before a header text
	new_html = new_html.replace(/<h1>&bull;/g, '<h1>');
	new_html = new_html.replace(/<h2>&bull;/g, '<h2>');
	new_html = new_html.replace(/<h3>&bull;/g, '<h3>');
	new_html = new_html.replace(/<h4>&bull;/g, '<h4>');
	new_html = new_html.replace(/<h5>&bull;/g, '<h5>');
	new_html = new_html.replace(/<h6>&bull;/g, '<h6>');
	
	// search for images and convert url
	html = new_html;
	new_html = '';
	from = 0;
	urls = /(<img src="?){1}(.*?)("? ){1}([\S\s]*?)(\/>){1}/img;
	while ((result = urls.exec(html)) != null) {
		//alert ("Matched at position " + result.index + " until " + urls.lastIndex + 
		//	"\n>" + result[0]  + "<" 
		//	+ "\nr1= " + result[1]
		//	+ "\nr2= " + result[2]
		//	+ "\nr3= " + result[3]
		//	+ "\nr4= " + result[4]
		//	+ "\nr5= " + result[5]); 
		new_html = new_html + html.substring(from, result.index) + result[1] + 
			groupidoImageURLConverter(result[2], 'img', true) + result[3] + result[4] + result[5];
		from = urls.lastIndex;
		//alert ("new_html=" + new_html);
	}
	// get the last part of the string
	new_html = new_html + html.substring(from, html.length);
	//alert ("new_html=" + new_html);
	
	return new_html;
}

// initialize tiny-mce editing for faq/news textareas
function faq_tinymce_init(class_name){
    // get all textarea-elements with the tiny-mce-class
    elements = $$('textarea.' + class_name);
    elements.each(function(value, index){
        editor = tinyMCE.get(value.id);
        if (typeof(editor) == 'undefined') {
            tinyMCE.execCommand('mceAddControl', false, value.id);
        }
        else {
			try {
            // remove existing editor and add a new one
			tinyMCE.remove(editor);
            tinyMCE.execCommand('mceAddControl', false, value.id);				
			}
			catch(err) {
				// Error Handling for IE which will in some cases not remove the editor
				// alert ("fehler: " + err);
	            tinyMCE.execCommand('mceAddControl', false, value.id);				
			}
        }
    });
}

// saves all faq/news-textareas
function faq_tinymce_save(class_name){
    // cleanup and save all textareas
    elements = $$('textarea.' + class_name);
    elements.each(function(value, index){
        //editor = tinyMCE.get(value.id);
        tinyMCE.execCommand('mceCleanup', false, value.id);
    });
    tinyMCE.triggerSave();
}


// login handling =============================================
function toggle_login_form(){
	// check if the function was called without having the login-form rendered
	// and activate the controller-action by a click to an unvisible button
	if ($('login_form_missing')) {
		//alert ("Login-Formular fehlt");
		$('login_form_missing').click();
	} else {
		    $('container_login').toggle();		
	}
    if ($('container_signup').style.display != "none") 
        $('container_signup').toggle();
}

function toggle_signup_form(){
    $('container_signup').toggle();
    if ($('container_login').style.display != "none") 
        $('container_login').toggle();
}


function slide_content(element, add_icon, remove_icon){
	// alert ('slide-content ' + add_icon + ' --- ' + remove_icon);
    new Effect.toggle($(element + "_content"), 'Slide', {
        duration: 0.2
    });
		
		if($(element + "_content").style.display == "")
			$(element + "_slide").src=add_icon;
		else
			$(element + "_slide").src=remove_icon;

			//alert($(element + "_content").style.display);
}

var win = null;
function NewWindow(mypage, myname, w, h){
    //alert(w + " " + h);
    LeftPosition = (screen.width) ? (screen.width - w) / 2 : 100;
    TopPosition = (screen.height) ? (screen.height - h) / 2 : 100;
    settings = 'width=' + w + ',height=' + h + ',top=' + TopPosition + ',left=' + LeftPosition + ',scrollbars=yes,location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=yes';
    win = window.open(mypage, myname, settings);
    
}

function init_menu(menu, current_page){
	//alert ("menu = " + menu + ", current_page = " + current_page);
	
    // get top of menu
    current_menu = $(menu);
    
    //get the current item
    current_item = $(menu + "_" + current_page);
    current_span = current_item.down('span');
    
    // set the classes
    current_item.className = "current_a";
    current_span.className = "current_span";
}

function highlight_menu(menu, item){

	//alert ("menu " + menu + " item " + item);
	
    // find old menu item and reset the class
    menu_start = $(menu);
	//alert ("menu start " + menu_start.innerHTML);
    current_item = menu_start.down(".current_a");
    current_span = current_item.down('span');
	//alert ("current_item " + current_item.className);
	//alert ("current_span " + current_span.className);
    current_item.className = "";
    current_span.className = "";
    
    // find the new menu item and set the class
    new_item = $(menu + "_" + item);
    new_span = new_item.down('span');
	//alert ("new_item " + new_item);
	//alert ("new_span " + new_span);
    new_item.className = "current_a";
    new_span.className = "current_span";
}



function closeObjectActions()
{
	$('object_action_menu').style.display = "none";
}


function move_user_address(addr_record, prefix){
    // convert activerecord 
    columns = addr_record.split('~');
    addr_attr = new Array();
    for (i = 0; i < columns.length;) {
        addr_attr[columns[i]] = columns[i + 1];
        i = i + 2;
    }
    
    // move the fiels to the order address elements
    fields = ['first_name', 'last_name', 'company', 'street_1', 'street_2', 'zip_code', 'location', 'country_id', 'phone'];
    for (i = 0; i < fields.length; i++) {
        //alert(prefix + fields[i] + "---" + addr_attr[fields[i]]);
        $(prefix + fields[i]).value = addr_attr[fields[i]];
    }
    
    // change the selectbox
    setSelectBoxValue(prefix + 'country_id', addr_attr['country_id']);
}

function move_user_pay_data(pay_data, prefix){
    // convert activerecord 
    columns = pay_data.split('~');
    pay_attr = new Array();
    for (i = 0; i < columns.length;) {
        pay_attr[columns[i]] = columns[i + 1];
        i = i + 2;
    }
    
    // move the fiels to the order address elements
    fields = ['account_owner', 'bank_name', 'bank_id_nr'];
    for (i = 0; i < fields.length; i++) {
        $(prefix + fields[i]).value = pay_attr[fields[i]];
    }
    
    // fields which are not in every form
    fields = ['bank_account_nr', 'bank_iban_nr'];
    for (i = 0; i < fields.length; i++) {
        if ($(prefix + fields[i]) != null) 
            $(prefix + fields[i]).value = pay_attr[fields[i]];
    }
}

function setSelectBoxValue(selectId, value){
    var selectBox = document.getElementById(selectId);
    for (i = 0; i < selectBox.length; i++) {
        selectBox.options[i].selected = false;
        if (value == selectBox.options[i].value) {
            selectBox.options[i].selected = true;
        }
    }
}

function change_order_summary(order_price, delivery_price) {
	$('order_offer_header_order_price').innerHTML    = order_price;
	$('order_offer_header_delivery_price').innerHTML = delivery_price;
}

function calculate_order_value() {
	var price = parseFloat($('order_max_price').value);
	var qty   = parseFloat($('order_quantity').value);
	if (qty.toString() == "NaN") {
		qty = parseFloat(0);
	}
	var order_value = (price * qty).toFixed(2);
	$('order_order_price').firstChild.data = order_value;
	//$('order_order_price').value = $('order_order_price_2').firstChild.data;
}

// Evaluates if the application is running in the top window or in 
// an iframe and saves this value in the form
function get_api_restart(elem_id) {
	//alert ("api_onload " + elem_id);
	elem = $(elem_id);
	if (self == top) {
		//alert ("self == top");
		elem.value = 'WINDOW';
	} else {
		//alert ("self != top");
		elem.value = 'IFRAME'
	}	
}

// Evaluates if the application is running in the top window or in
// an iframe and either opens a new window or replaces the current window
function api_switch_unrestricted(elem, link) {
	//alert ("elem " + link);
	if (self == top) {
		//alert ("self == top");
		location.replace(link);
			
	} else {
		//alert ("self != top");
		window.open(link,'_blank');	
	}
}

// test functions ======================================
function api_change_color(input_elem) {
	color_box = input_elem.id + "_show";
	$(color_box).style.backgroundColor = input_elem.value;
}

