// JavaScript Document



function setGroup(ob){
    if(!ob.value) return;
	
    $('type').innerHTML = '';
	
    new Ajax.Request('/ecat/searchgroup/id/'+ob.value+'/request/ajax',{
	method:'get',
	onSuccess: function(transport){
	    var response = transport.responseText || "no response text";
	    $el = $('manuf');
	    $el.innerHTML = response;
	},
	onFailure: function(){
	    alert('Something went wrong...')
	}
    });
}

function setType(ob){
    if(!ob.value) return;
	
    var ecat = $('ecat');
    var id = ecat.value;
	
    if(!id) return;
	
    new Ajax.Request('/ecat/searchtype/id/'+id+'/man/'+ob.value+'/request/ajax',{
	method:'get',
	onSuccess: function(transport){
	    var response = transport.responseText || "no response text";
	    $el = $('type');
	    $el.innerHTML = response;
	},
	onFailure: function(){
	    alert('Something went wrong...')
	}
    });
}

function getProducts(ob){
    var filter = ob.value;
    var id = $('ecat').value;
    var man = $('manufacturer').value;
	
    if(!filter || !id || !man) return;
    window.location = "/ecat/search/id/"+id+"/filter/"+filter+"/man/"+man;
}

function redirect(url){
    window.location=url;

}

function panelShow(id, m){
    if(panel_max < 2) return;
    window.clearTimeout(panel_time);
    for(i=0; i<panel_max; i++){
	var el = $('panel_'+i);
	if(el){
	    el.hide();
	    $('mpanel_'+i).style.background = '#CCC';
	}
    }
    $(id).show();
    m.style.background = '#999';
}

function initPanel(no){
    if(no){
	panel = 0;
	panel_max = no;
    }
    if(panel_max < 2) return;
    panel_time = window.setTimeout(function() {
	rotatePanel();
    },
    3000);
}

function rotatePanel(){
    if(panel_max < 2) return;
    panel++;
    if(panel >= panel_max)
	panel = 0;
    panelShow('panel_'+panel, $('mpanel_'+panel));
    panel_time = window.setTimeout(function() {
	rotatePanel();
    },
    3000);
}

function stopPanel(){
    if(panel_max < 2) return;
    window.clearTimeout(panel_time);
}

function text2pass(pass, passcontainer){ 
    if($(pass).value == 'slaptažodis'){
	$(passcontainer).innerHTML="<input id=\""+pass+"\" name=\"password\" type=\"password\" class=\"fld\" style=\"width:100px; color:#999; padding:2px\" size=\"15\" maxlength=\"60\"/>";
	var passbox = $(pass);
	passbox.focus();
	passbox.focus();
	
	passbox.onblur = function(){
	    if(!$(pass).value)
		$(passcontainer).innerHTML="<input id='"+pass+"' type='text' class='fld' value='slaptažodis' onFocus=\"text2pass('"+pass+"','"+passcontainer+"')\" style=\"width:100px; color:#999; padding:2px\" size=\"15\" maxlength=\"60\">" ;
	}
    }
}

function questions(){
    createWin({
	title:'Klausti/Siūlyti',
	width:373,
	id:'quest'
	}, '<table cellpadding="2" cellspacing="2"><tr><td><label><input name="type" type="radio" value="1" checked="checked" id="q_type"/>Klausti</label><br /><label><input type="radio" name="type" value="2"/>Siūlyti</label></td></tr><tr><td>Vardas*<br><input type="text" name="textfield" id="q_name" class="fld" size="40"></td></tr><tr><td>Norėčiau atsakymą gauti šiuo el.paštu*<br><input type="text" name="textfield2" id="q_email" class="fld" size="40"></td></tr><tr><td>Tekstas*<br><textarea name="textarea" id="q_text" cols="60" rows="5" class="fld" style="width:100%"></textarea></td></tr><tr><td colspan="2"><input type="button" name="button" id="button" value="Siųsti" onClick="q_submit(this)"></td></tr></table>');
}

function q_submit(win){
    var name = $('q_name').value;
    var email = $('q_email').value;
    var text = $('q_text').value;
	var type = ($('q_type').checked == true ? 1 : 2);
    if(!name || !text || !email){
	if($('q_error'))
	    $('q_error').update('Prašome užpildyti privalomus laukus.');
	else
	    $('questwincontent').insert({
		top: '<div style="padding:4px; color:#f00" id="q_error">Prašome užpildyti privalomus laukus.</div>'
		});
	return;
    }
    new Ajax.Request('/faq/submit', {
	method: 'post',
	onSuccess: function(transport) {
	    if(transport.responseText == 'ok')
		$('questwinclose').onclick();
	    else{
		if($('q_error'))
		    $('q_error').update(transport.responseText);
		else
		    $('questwincontent').insert({
			top: '<div style="padding:4px; color:#f00" id="q_error">'+transport.responseText+'</div>'
			});
	    }
	},
	parameters:{
	    name:name,
	    email:email,
	    text:text,
	    type:type
	}
    });
}

function q_answer(el){
    if($('a_'+el.id)){
	var el = $('a_'+el.id);
	if(el.style.display == 'none'){
	    Effect.BlindDown(el, {
		duration: 1
	    });
	    return;
	}else if(el.lang != 'load'){
	    Effect.BlindUp(el, {
		duration: 1
	    });
	    return;
	}

    }
    el.style.cursor = 'wait';
    new Ajax.Request('/faq/get', {
	method: 'post',
	onSuccess: function(transport) {
	    var id = transport.request.parameters.id;
	    var el = $(id);
	    if($(id)){
		el.update(transport.responseText);
		el.style.cursor = 'pointer';
		el.lang = '';
		Effect.BlindDown(id, {
		    duration: 1
		});
	    }else{
		el.style.cursor = 'pointer';
		el.insert({
		    after: '<div id="a_'+id+'" class="q_answer" style="visibility:none"><div>'+transport.responseText+'</div></div>'
		    });
		Effect.BlindDown('a_'+id, {
		    duration: 1
		});
	    }
	},
	parameters:{
	    id:el.id
	    }
    })
}

function q_getGroup(el, opened){
    var opened = 1;
    var id = el.id;
    q_closeAll();
    el.removeClassName('q_title_disabled');
    var el = $('q_content');

    el.style.cursor = 'wait';

    new Ajax.Request('/faq/getGroup', {
	method: 'post',
	onSuccess: function(transport) {
	    var id = transport.request.parameters.id;
	    el.style.cursor = 'pointer';
	    el.update(transport.responseText);
	    Effect.BlindDown(el);
	},
	parameters:{
	    id:id,
	    open:opened
	}
    })
}

function q_closeAll(){
    var groups = $$('div.q_title');
    groups.each(function(e){
	e.addClassName('q_title_disabled');
    });

}

function onPage(obj, location){
    var page = obj.options[obj.selectedIndex].value;
    window.location = location + '&page=' + page;
}

function f_disable(fields){
    for (i = 0; i < fields.length; i++) {
	if ($(fields[i]))
	    $(fields[i]).disabled = true;
    }
}

function f_enable(fields){
    for (i = 0; i < fields.length; i++) {
	if ($(fields[i]))
	    $(fields[i]).disabled = false;
    }
}

function initTabs(prefix){
    this.prefix = prefix;
    var res = $$('.' + prefix + '_panel');
    if (!res.length)
	return;
    var html = '';
    panels = [];
    var title = $('title');
    var th;
    if(title.innerHTML){
	title.setStyle({
	    height:'auto'
	});
	th = title.getHeight();
    }else{
	title.remove();
	th = 0;
    }

    var h = $('body').getHeight() - 64 - th - 54; // 23 -tab control height,
    // 30 - tab padding

    var outerbp = $('outer_bottom_panel');
    if (outerbp) {
	var outer_h = outerbp.getHeight();
	h = h - outer_h;
    }
    for (i = 0; i < res.length; i++) {
	var h1;
	if (res[i].title)
	    html += '<div class="tab" onClick="tab(\'' + i + '\', \'' + prefix + '\')" id="pc' + i + '"><div>' + res[i].title + '</div></div>';
	panels[i] = res[i];
	if (i > 0)
	    res[i].hide();

	var inner = res[i].down('.inner_bottom_panel');
	if (inner && inner != '') {
	    inner.setStyle({
		position: 'absolute',
		bottom: '20px',
		left: '202px',
		width: $('tb_content').getWidth() + 'px'
	    });

	    res[i].setStyle({
		marginBottom: '41px'
	    });
	    h1 = h - 41;
	}else{
	    h1 = h - 2;
	}

	res[i].setStyle({
	    height: h1 + 'px',
	    padding: '13px'
	});
    }
    if ($(prefix + '_button'))
	$(prefix + '_button').onclick = function(){
	    tab(false, prefix);
	}
    $('tab_control').innerHTML = html + '<div style="clear:left; height:0px"></div>';
    current_tab = 0;
    $('pc0').className = 'tab_active';
}

function tab(nr, prefix){

    if (!nr) {
	nr = parseInt(current_tab) + 1;
    }

    if (nr == current_tab)
	return;

    panels[current_tab].toggle();
    $('pc' + current_tab).className = 'tab';
    panels[nr].toggle();
    current_tab = nr;
    $('pc' + nr).className = 'tab_active';
    var button = $(prefix + '_button');
    if (!button)
	return;
    if (nr == panels.length - 1) {
	button.value = 'Senden';
	button.onclick = function(evt){
	    if (wFORMS.formValidation(evt)) {
		document.forms['myform'].submit();
	    }
	}
    }
    else {
	button.value = 'weiter';
	button.onclick = function(){
	    tab(false, prefix);
	}
    }
}

function initCalendar(){
    var cal = $$('.calendar');
    if (!cal)
	return;
    var calendar = new CalendarPopup('_calendar');
    calendar.setCssPrefix("TEST");
    for (i = 0; i < cal.length; i++) {
	cal[i].onclick = function(e){
	    if (e)
		var target = e.target;
	    else
		var target = event.srcElement;

	    if (!target.id)
		target.id = 'rnd' + Math.ceil(Math.random() * 1000);
	    calendar.select(target, target.id, 'dd.MM.yyyy')
	}
    }
    initCalendarMonth();
}

function initCalendarMonth(){

    var cal = $$('.calendarMonth');
    if (!cal)
	return;

    var calen = new Array();

    for (i = 0; i < cal.length; i++) {
	if (cal[i].readOnly)
	    continue;

	calen[i] = new CalendarPopup('_calendar');
	calen[i].setDisplayType("month");
	calen[i].setReturnMonthFunction('ReturnMonth');
	calen[i].showYearNavigation();
	calen[i].setCssPrefix("TEST");
	// calen[i][i] = cal[i];
	cal[i].no = i;
	cal[i].onclick = function(e){
	    if (e)
		var target = e.target;
	    else
		var target = event.srcElement;

	    if (!target.id)
		target.id = 'rnd' + Math.ceil(Math.random() * 1000);
	    calen[this.no].showCalendar(target.id);
	}
    }
}

function ReturnMonth(y, m){
    $(input).value = m + "/" + y;
}

function goto(linkas){
    window.location = linkas;
}

function createWin(options, content){

    if(options.id){
	var prefix = options.id;
	if($(prefix))
	    return;
    }else{
	var prefix = Math.ceil(Math.random()*10000)+'_';
    }
    var title = options.title;
    var width = options.width;
    var divs = '';
    if(options.modal)
	divs = '<div id="winmodal"></div>';
    $('body').insert(divs+'<div id="'+prefix+'" class="wincontainer"><div id="'+prefix+'winbody" class="winbody"><div id="'+prefix+'wintitle" class="wintitle"><div id="'+prefix+'wintitlecontent" class="wintitlecontent">' + title + '</div><div id="'+prefix+'winclose" class="winclose"></div><div style="clear:left"></div></div><div id="'+prefix+'wincontent" class="wincontent"></div></div></div>');

    var win = $(prefix);
    var body = $(prefix+'winbody');


    var wintitle = $(prefix+'wintitle');
    wintitle.alt = prefix;
    var closeicon = $(prefix+'winclose');
    closeicon.onclick = function(){
	//selectStart();
	var win = $(prefix);
	win.update('');
	win.remove();
	if($('winmodal')){
	    $('winmodal').remove();

	}
    }
    win.close = closeicon.onclick;
    win.setStyle({
	width: (width+6) + 'px'
    });
    body.setStyle({
	width: width + 'px',
	background:options.bcolor ? options.bcolor : '#fff'
    });


    $(prefix+'wincontent').update(content);

    if(options.closeButton){
	$(options.closeButton).onclick = closeicon.onclick;
    }
    if(options.okButton){
	$('okbutton').onclick = options.okButton;
    }

    if(options.height){
	$(prefix+'wincontent').setStyle({
	    height:options.height+'px',
	    overflow:'auto'
	});
    }else{
	win.setStyle({
	    height:(body.getHeight()+8)+'px'
	    });
    }

    if(!options.position || options.position == 'm')
	win.setStyle({
	    left: parseInt(($('body').getWidth() - body.getWidth()) / 2) + 'px',
	    top: parseInt((($('body').getHeight() - win.getHeight()) / 3) + document.viewport.getScrollOffsets().top) + 'px'
	});
    else if(options.position == 'rb'){ // right bottom
	win.setStyle({
	    left: parseInt(($('body').getWidth() - body.getWidth() - 1)) + 'px',
	    top: parseInt(($('body').getHeight() - body.getHeight() - 1)) + 'px'
	});

    }
    Effect.DropShadow(prefix);
    new Draggable(win,{
	handle: prefix+'wintitle'
	});
    return $(prefix+'wincontent');
}

function loadWin(width, title, url){

    new Ajax.Request(url, {
	method: 'get',
	onSuccess: function(transport){
	    createWin(width, title);
	    if(transport.responseText == 0)
		$('wincontent').update('Error loading content. Please check the Internet connection');
	    else
		$('wincontent').update(transport.responseText);
	}
    });

}

function selectStop(){
    document.onselectstart = function(){
	return false;
    }
    document.onmousedown = function(){
	return false;
    }
    document.onselectstart = function(){
	return false;
    }
    document.onmousemove = function(){
	return false;
    }
}

function selectStart(){
    document.onselectstart = function(){
	return true;
    }
    document.onmousedown = function(){
    }
    document.onselectstart = function(){
    }
    document.onmousemove = function(){
    }
}

function startDrag(event){
    if(event.target.alt)
	var prefix = event.target.alt;
    else
	var prefix = event.target.up().alt;

    dragObj = $(prefix+'winbody');
    $(prefix+'wincontent').hide();
    dragObj.setOpacity(0.5);

    cursorStartX = Event.pointerX(event);
    cursorStartY = Event.pointerY(event);
    elementStartX = parseInt(dragObj.getStyle('left'), 10);
    elementStartY = parseInt(dragObj.getStyle('top'), 10);

    Event.observe($('body'), 'mousemove', dragGofn);
    Event.observe(dragObj, 'mouseup', dragStopfn);
}

function dragGo(event){
    if (dragObj) {
	var x, y;
	x = Event.pointerX(event);
	y = Event.pointerY(event);
	dragObj.style.left = (x - cursorStartX + elementStartX) + "px";
	dragObj.style.top = (y - cursorStartY + elementStartY) + "px";
    }
    Event.stop(event);
}

function dragStop(event){
    if(event.target.alt)
	var prefix = event.target.alt;
    else
	var prefix = event.target.up().alt;

    $(prefix+'wincontent').show();
    dragObj.setOpacity(1);
    // Stop capturing mousemove and mouseup events.
    Event.stopObserving(dragObj, 'mousemove', dragGofn);
    Event.stopObserving(dragObj, 'mouseup', dragStopfn);
    dragObj = null;
    Event.stop(event);
}

function showMessage(options, content){
    return createWin(options, content);
}
Effect = {};
Effect.DropShadow = function(el){
    var element = $(el);

    var i1 = new Element('div', {
	'class': 'i1'
    });
    var i2 = new Element('div', {
	'class': 'i2'
    });
    var i3 = new Element('div', {
	'class': 'i3 cf'
    });

    i2.appendChild(i3);
    i1.appendChild(i2);

    $A(element.childNodes).each(function(e){
	i3.appendChild(e);
    });

    var bfunc = function(className){
	var e = new Element('div', {
	    'class': className
	});
	e.appendChild(new Element('div'));
	return e;
    };

    element.addClassName('cp');
    element.appendChild(bfunc('bt'));
    element.appendChild(i1);
    element.appendChild(bfunc('bb'));
};

