// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
function attach_send_file(){
    currentOmniCmsInterface.showIndicator()
    $('upload_form').submit();
    
}
function handleResponse(id) {
  currentOmniCmsInterface.hideIndicator()
  if ($('omnicms_plugin_name')) {$('omnicms_plugin_name').onchange()}
}

function findAndSelect(obj,val)
{
	if (obj == null || val == null)
		return false;

	for (i=0; i < obj.length; i++)
	{
		if (obj.options[i].value == val)
		{
			obj.options[i].selected = true;
			return true;
		}
	}
    return false;
}	


//--------------------------------------------------//
//              Do pluginu packages                 //
//--------------------------------------------------//

function SDC_package_proceed_payment(url)
{
	window.open("https://cs.globetrack.ie/flextravelsdc/package_payment"+url,"Paymanet","scrollbars=1,status=0,toolbar=0,height=300,width=950");	
}

function package_people_change(type)
{
    adults = 0
    children = 0
    var items = $$(".package_scenario").findAll(function(obj) {
        if (obj.checked)
        {
            i = obj.id.split('_')
            ids[ids.length] = i[2]
            adults+= $('adults_'+i[2]).value * 1
            if ($('children_'+i[2]))
                children+= $('children_'+i[2]).value * 1            
        }
    });    

    new Ajax.Request('/globetrack_packages/people_choosen/'+type, {asynchronous:true, evalScripts:true, parameters:'adults='+adults+'&children='+children})
    show_package_price()
}

function show_package_price()
{
    ids = new Array()

    var items = $$(".package_scenario").findAll(function(obj) {
        if (obj.checked)
        {
            i = obj.id.split('_')
            ids[ids.length] = i[2]            
        }
    });    
    adults = 0;
    children = 0;
    p_adults = 0;
    p_children = 0;    
    for (i=0; i< ids.length; i++)
        if (additionas_services && additionas_services[''+ids[i]+''])
        {
            serv = additionas_services[''+ids[i]+'']
            if (serv['basic'] && serv['basic'] != "")
            {
                acc = serv['basic'].split("|")
                for (a=0; a < acc.length; a++)
                {
                    if (acc[a] == "") continue
                    _a = acc[a].split(";")
                    adults+= $('adults_'+ids[i]).value * 1
                    if (!isNaN(_a[2] * 1))
                        p_adults+= (_a[2] * 1) * ($('adults_'+ids[i]).value * 1)
                    if (!$('children_'+ids[i])) continue
                    children+= $('children_'+ids[i]).value * 1
                    if (!isNaN(_a[3] * 1))
                        p_children+= (_a[3] * 1) * ($('children_'+ids[i]).value * 1)
                }
            }
        }        
     $('package_scenario_total_price').innerHTML = "Total price: "+(p_adults+p_children)
}

function show_package_details()
{
    ids = new Array()

    var items = $$(".package_scenario").findAll(function(obj) {
        i = obj.id.split('_')
        if (obj.checked)
        {
            ids[ids.length] = i[2]
            if ($('adults_'+i[2]).selectedIndex == 0)
            {
                $('adults_'+i[2]).selectedIndex = 1
                $('adults_'+i[2]).onchange()
            }                
                

            if ($('children_'+i[2]))            
                if ($('children_'+i[2]).selectedIndex == 0)
                {
                    $('children_'+i[2]).selectedIndex = 1
                    $('children_'+i[2]).onchange()
                }
            
        }
        else
        {
            if ($('adults_'+i[2]).selectedIndex != 0)
            {
                $('adults_'+i[2]).selectedIndex = 0
                $('adults_'+i[2]).onchange()
            }

            if ($('children_'+i[2]))
                if ($('children_'+i[2]).selectedIndex != 0)
                {
                    $('children_'+i[2]).selectedIndex = 0
                    $('children_'+i[2]).onchange()                    
                }
        }            
    });
    accommodation_html = ""
    transport_html = ""
    extras_html = ""

    if (ids.length>0)
        $('package_scenario_total_price').innerHTML = ""
        
    for (i=0; i< ids.length; i++)
        if (additionas_services && additionas_services[''+ids[i]+''])
        {
            serv = additionas_services[''+ids[i]+'']
            if (serv['accommodation'] && serv['accommodation'] != "")
            {
                acc = serv['accommodation'].split("|")
                for (a=0; a < acc.length; a++)
                {
                    if (acc[a] == "") continue
                    _a = acc[a].split(";")
                    accommodation_html+= "<p>Hotel:"+_a[0]+"</p>"
                    accommodation_html+= "<p>Room:"+_a[1]+"</p>"                    
                }
            }
            if (serv['transport'] && serv['transport'] != "")
            {
                acc = serv['transport'].split("|")
                for (a=0; a < acc.length; a++)
                {
                    if (acc[a] == "") continue
                    _a = acc[a].split(";")
                    transport_html+= "<p>Name:"+_a[0]+"</p>"
                    transport_html+= "<p>Descr:"+_a[1]+"</p>"                    
                }
            }
            if (serv['extras'] && serv['extras'] != "")
            {
                acc = serv['extras'].split("|")
                for (a=0; a < acc.length; a++)
                {
                    if (acc[a] == "") continue
                    _a = acc[a].split(";")
                    extras_html+= "<p>Name:"+_a[0]+"</p>"
                    extras_html+= "<p>Descr:"+_a[1]+"</p>"                    
                }
            }
        }
    if (accommodation_html != "")
        accommodation_html = "<h4>Accommodation</h4>"+accommodation_html
    if (transport_html != "")
        transport_html = "<h4>Transport</h4>"+transport_html
    if (extras_html != "")
        extras_html = "<h4>Extras</h4>"+extras_html

    $('package_scenario_accommodation').innerHTML = accommodation_html
    $('package_scenario_transport').innerHTML = transport_html
    $('package_scenario_extras').innerHTML = extras_html        
    show_package_price()
}

var PageSelector = Class.create();
PageSelector.prototype = {
	dialogClassName: 'dialog',
	checkPlaceId: 'hrefPageSelectorPlace',
	selectorsClassNames: 'omnicms_markup_page_selector', 
	loadPageUrl: '/page/tree?is_root=1&hide_additional=1&clean_container=1&',
	
	initialize: function(clickElement, newElementId, inputId) {
		if(clickElement==null) return;
		if(newElementId.gsub(/[\d]+/, '')=='')
			newElementId = 'pageSelector' + newElementId;
		this.hideOpened();
		this.clickElement = $(clickElement);
		if($(newElementId)==null) {
			var el = $(document.createElement('div'));
			el.addClassName(this.selectorsClassNames);
			el.setAttribute('id', newElementId);
			if($(this.checkPlaceId)==null)
				this.getDialog().appendChild(el);
			else {
				$(this.checkPlaceId).appendChild(el);
				Position.absolutize($(this.checkPlaceId));
			}
		}
		this.container = $(newElementId);
		if($(this.checkPlaceId)==null) {
			var offs = Position.cumulativeOffset(this.clickElement), 
				dialOffset = Position.cumulativeOffset(this.getDialog()),
				y = offs[1]-dialOffset[1];
			if(y>300 && Prototype.Browser.IE) y = 300;
			this.container.setStyle({'left': (offs[0]-dialOffset[0])+'px', 'top': y+'px'});
		}
		else {
			$(this.checkPlaceId).setStyle({
				'left': '86px', 
				'width': '260px',
				'background': '#FFF', 
				'border': 'solid 1px #000',
				'height': '200px',
				'overflow' :'auto'
			});
			$(this.checkPlaceId).show();
		}
		
		this.container.setStyle({'zIndex': '9999'});
		this.container.setStyle({'display': 'inline'});
		this.container.update('Loading...');
		this.loadContent(inputId);
		this.inputId = inputId;
		$(this.inputId).connectedPageSelector = this;
		this.startHighlightInput();
	},
	
	getDialog: function() {
		if(typeof this.dialog!="undefined")
			return this.dialog;
		var limit = 1000;
		this.dialog = this.clickElement;
		while(!this.dialog.hasClassName(this.dialogClassName) && (limit--)>0) this.dialog = $(this.dialog.up());
		return this.dialog;
	},
	hideOpened: function() {
		$A($(document.body).getElementsByClassName(this.selectorsClassNames)).each(function(element){
			try {$(element).connectedPageSelector.updateTextAndClose($(element).connectedPageSelector.inputId);} catch(e) {}
			try {$(element).remove();} catch(e) {}
		});
	},
	loadContent: function(inputId) {
		new Ajax.Request(this.loadPageUrl + 'node='+this.container.id+'&inputId='+inputId, {
			onSuccess: function(resp) {
				this.mouseOnObserver = this.mouseOver.bindAsEventListener(this);
				Event.observe(this.container, 'mouseover', this.mouseOnObserver);
				this.mouseOutObserver = this.mouseOut.bindAsEventListener(this);
				Event.observe(this.container, 'mouseout', this.mouseOutObserver);
			}.bind(this)
		});
	},
	mouseOver: function(event) {
		if(typeof this.lastOnDivTmt!="undefined")
			clearTimeout(this.lastOnDivTmt);
	},
	mouseOut: function(event) {
		this.lastOnDivTmt = setTimeout(function(){
			this.updateTextAndClose(this.inputId);
		}.bind(this), 2000);
	},
	updateTextAndClose: function(inputId, pageId) {
		var sep = $($(inputId).connectedPageSelector.checkPlaceId);
		if(pageId!=null) {
			$(inputId).value = sep==null ? pageId : '/page/index/'+pageId;
		}
		$(inputId).connectedPageSelector.stopHighlightInput();
		try {$(inputId).connectedPageSelector.container.remove();} catch(e) {}
		if(sep!=null) sep.hide();
	},
	startHighlightInput: function() {
		this.lastBorder = $(this.inputId).getStyle('border');
		this.cr = 255;
		this.hightLightInput();
	},
	hightLightInput: function() {
		this.lastTimeout = setTimeout(function() {
			if($(this.inputId)==null) return;
			$(this.inputId).setStyle({'border': 'solid 1px #'+[this.cr, this.cr, this.cr].invoke('toColorPart').join('')});
			this.cr -= 30;
			if(this.cr<0) this.cr = 255;
			this.hightLightInput();
		}.bind(this), 100);
	},
	stopHighlightInput: function() {
		clearTimeout(this.lastTimeout);
		if(typeof this.lastBorder!="undefined")
			$(this.inputId).setStyle({'border': this.lastBorder});
		else
			$(this.inputId).setStyle({'border': 'solid 1px #999'});
		Event.stopObserving(this.container, 'mouseover', this.mouseOnObserver);
		Event.stopObserving(this.container, 'mouseout', this.mouseOutObserver);
		clearTimeout(this.lastOnDivTmt);
	}
};

var OmniNewsletter = {
	checkUrl: function() {
		var url = (new String(document.location)).gsub(/#.*$/, '').gsub(/[^\?]+\?/, ''), h = $H(url.toQueryParams());
		if(typeof(h.message)!="undefined") {
			this.showMessage(h.message.escapeHTML(), true);
			setTimeout(function() {new Effect.Pulsate(this.showElement);}.bind(this), 1000);
		}
	},
	
	sendForm: function(clickElement, isSignOut) {
		var form = null, max = 100, params = {};
		while($(clickElement).up().tagName.toLowerCase()!='form' && (max--)>0) 
			clickElement = $(clickElement).up();
		form = $(clickElement).up();
		if(form.tagName.toLowerCase()!='form') {
			alert('Sorry, unable to find form element.');
			return false;
		}
		params = $H(Form.serialize($(form)).toQueryParams());
		params.email = params.email.strip();
		if(params.email=='' || params.email.gsub(/^[a-z0-9\-\._]+@[a-z0-9\-\.]+\.[a-z0-9]{2,}$/i, '')!='') {
			alert('Please enter correct email address.');
			return false;
		}
		if(isSignOut) params.remove_from_list = 1;
		params.rand = Math.random();
		params.url = (new String(document.location)).gsub(/#.*$/, '');
		this.form = $(form);
		this.showMessage('Loading...'); 
		new Ajax.Request(['', 'newsletter', 'add'].join('/'), {
			parameters: params.toQueryString(), 
			onComplete: function(response) {
				this.showMessage(response.responseText, true);
			}.bind(this)
		});
	},
	
	showMessage: function(result, irregular) {
		if(typeof(this.showElement)=='undefined') {
			if(typeof(this.form)=="undefined") {
				try {
					this.form = document.body.getElementsByTagName('form').item(0);
				}
				catch(e) {}
			}
			this.showElement = $(document.createElement('p'));
			this.form.up().insertBefore(this.showElement, this.form.next());
		}
		this.showElement.hide();
		this.showElement.setStyle({padding: '3px', color: (irregular ? 'red' : '')});			
		this.showElement.update(result);
		setTimeout(function() {new Effect.Appear(this.showElement, {duration: 0.25});}.bind(this), irregular ? 310 : 10);
	}
};