/* Include's scrollTo plugin ( author Ariel Flesler, @version 1.4.2 ) */

/** Globals **/
var _epo_links = {};
var _epo_labels = {};
var _epo_package = {};
var _epo_config = {};
var _request = false
var _redirectTimeout = false;
var formIdQuery;


function changeLang() {
	if ($('#chLang').val() != '') {
		location.href = $('#chLang').val();
	}
}

function changeService() {
	if ($('#eurSevices').val() != '') {
		location.href = $('#eurSevices').val();
	}
}

function refreshShopingCard(){
			
//	var total = $('#oPpcPrice').text()*1 + $('#oMultiPrice').text()*1 + $('#oCttCount').text() * $('#oCttPrice').text();
    var total = $('#oPpcPrice').text()*1 + $('#oMultiPrice').text()*1;
	$('#oTotal').text(total);
}

var _msk = {};

(function(){

/** Global onLoad **/
$(document).ready(function(){
	$('#modalBoxBusscardDetail').jqm({ toTop: true, onShow: _msk.correlModal});
	$('#busscardDetail').click(function(){
		$('#modalBoxBusscardDetail').jqmShow();
	});	
	
	$('input.phoneNumber').change(function(){
		$(this).val($(this).val().replace(/\s/g, ''));
	});
});
/** Global onLoad Stop **/

var 
itemsCache = {},
formData = {},
formErrors = {},
formFieldStorage = {};

_msk = {

INPUT_STATUS_OK : 1,
INPUT_STATUS_ERR : 2,
INPUT_STATUS_REQ : 3,

addEvent : function(ref, event, func){
	if (ref.addEventListener){
		ref.addEventListener(event, func, false);
 	}else{
 		ref.attachEvent("on"+event, func);
 	}
},

setIconStatus : function(oIco, status){
	
	oIco.removeClass('req').removeClass('err').removeClass('ok');
	
	var cls = '';
	
	switch(status){
		case this.INPUT_STATUS_OK:
			cls = 'ok';
		break;
		case this.INPUT_STATUS_ERR:
			cls = 'err';
		break;
		case this.INPUT_STATUS_REQ:
			cls = 'req';	
		break;
	}
	
	if(cls){
		oIco.addClass(cls);
	}	
},

isObject: function(A){
	return(A&&(typeof A==="object"||YAHOO.lang.isFunction(A)))||false;
},
isArray: function(v){
	return v&&typeof v.length=="number"&&typeof v.splice=="function";
},

getErrorList : function(errors){
	var errList = [];
	if(errors){
		errList.push('<ul class="errors">');
		
		if( _msk.isArray(errors) ){
			for(var i=0;i<errors.length;i++){
				errList.push('<li>'+ errors[i] +'</li>');
			};
		}else if( _msk.isObject(errors) ){
			for(k in errors){
				errList.push('<li>'+ errors[k] +'</li>');
			};
		}
		
		errList.push('</ul>');
	}	
	
 return errList.join("");
},

assignErrors : function(obj, errors, ico){	
	obj.after(this.getErrorList(errors));
	
	if(!ico){
		ico = obj.parent().children().filter('.form-icon')
	}
	
	this.setIconStatus(ico, this.INPUT_STATUS_ERR);
},

cleanupErrors : function(){
	$(formIdQuery + ' .errors, '+ formIdQuery +' .error_img').remove();
	$(formIdQuery + ' .form-icon').each(function(i, el){
		$(el).removeClass('err').removeClass('ok');
	});
},

/*************************/
correlModal : function(modal){
	
	var modalWindow = modal.w;
	var modalHeight = modalWindow.height();	
	var docHeight 	= $(document).height();
	var scrollTop 	= $(document).scrollTop();
	var viewPortHeight = $(window).height();	
	
	var top = 0;
	
	if( modalHeight <= viewPortHeight ){
		top = (viewPortHeight - modalHeight)/2 + scrollTop;
	}
	
	else{
		if( modalHeight < docHeight ){		
			
			if( (modalHeight + scrollTop) < docHeight ){
				top = scrollTop;	
			}
			
			else{
				top = docHeight - modalHeight;
			}
		}
	}
	
	
	modalWindow.css('top', top + 'px').show();
},

handleTooltip : function(){

	$('.toolTip').each(function()	{
		$(this).qtip({
			content: $(this).next('p.toolTip_cnt').text(),			
			show: {
				solo: true,
				ready: false,
				when: 'mouseover',
				effect: 'fade'
			},		
			hide: { when: 'mouseout', fixed: true },		
			position: {
				corner: {
					target: 'rightMiddle',
					tooltip: 'leftMiddle'
				},
				adjust: { x: 8, y: 0 }
			},
			style: {
				border: {width: 0,radius: 0},
				padding: 20,
				width: 200,
				background: '#e9fdb5',
				'color': '#505050',
				'overflow': 'visible'				
			},	
			api: {
		        onRender : function (){
		           this.elements.content.find('.toolTipBox_close').click(this.hide);
		        }
	      	}
		});
	});
},

showFreeCall : function(){
	$('#call_tip').hide();
	$('#call_tip_active').show();
},

hideFreeCall : function(){
	$('#call_tip_active').hide();
	$('#call_tip').show();
},

handleFieldsLookAndFeel: function(){
		
	
	$(formIdQuery + ' :input').each(function(i, el){		
		addFieldHandle( $(el) );
	});	
	
	$(formIdQuery + ' textarea').each(function(i, el){
				
		addFieldHandle( $(el) );
	});
	
	function addFieldHandle( $el ){
	
		var def = $el.attr('title');	
		
		$el.focus(function(e){			
			$(this).removeClass('filled').addClass('focus');			
		})		
		.blur(function(e){
			var v = $(this).val();
			$(this).removeClass('focus');
			if( !def || (def && $(this).val() != def) ){
				if(v && v != 0){		
					$(this).addClass('filled');
				}				
			}
		});
	}	
	
},

handleInputCorrectness : function( requirementsOptions, iconsOptions ){	
	
	var blurMethod = function(obj, requirements){
		
		var v = obj.val(), len = v.length, err = [];
		if(requirements['required']){
			if(!v || !v.length || (requirements['defaultValue'] && requirements['defaultValue'] == v))
			{
				err.push('required');
			}
		}
		
		if(!err.length)
		for(k in requirements){
			switch(k){
				case 'not_null':
					if(v == 0 || v == "0")
					{
						err.push('not_null');
					}
				break;
				case 'minlen':
					if(len < requirements['minlen'])
					{
						err.push('minlen');
					}
				break;
				case 'maxlen':
					if(len > requirements['maxlen'])
					{
						err.push('maxlen');
					}
				break;
				case 'email_format':
					if( !v.match(/^([a-z0-9\-\_\.&])+@([a-z0-9\-\_\.&])+\.(([a-z]{2,4})|travel|museum)$/gi) ){
						err.push('email_format');
					};
				break;
				case 'phone_number':
					if( v.match(/([^ 0-9\/\.-]+)/gi ) ){
						err.push('phone_number');
					}
				break;						
			}
		}		

		var oStatus;
		if(iconsOptions){
			if(iconsOptions[obj.attr('name')] == 'parent'){
				oStatus	= obj.parent().parent().children().filter('.form-icon');
			}
		}		
		if(!oStatus){
			oStatus = obj.parent().children().filter('.form-icon');
		}		
		
		$(this).next('ul.errors').remove();
		
		if(err.length){
			_msk.setIconStatus(oStatus, _msk.INPUT_STATUS_ERR);
		}else{ 
			_msk.setIconStatus(oStatus, _msk.INPUT_STATUS_OK);
			obj.parent().children().filter('ul.errors').remove();
		}
	};
	
	var addBlurEvent = function(key, value){
		$(formIdQuery + ' [name="'+ key +'"]').blur(function(){
			blurMethod($(this), value);
		});	
	};

	for(k in requirementsOptions) addBlurEvent(k, requirementsOptions[k]);
},

floatingPreview : function(){
	var 
	name = "#ppcPreview",
	startPos =  $(name).offset().top,	
	itemHeight = $(name).height(),
	viewPortHeight = $(window).height(),
	getHeightMax = function(){ return ($('#ppcForm').height() + startPos)  - itemHeight; };
		
	$(window).resize(function(){ viewPortHeight = $(window).height(); });
	$(window).scroll(function () {
		if(viewPortHeight < itemHeight) return false;
		var offset = startPos + $(document).scrollTop();
		if(offset > startPos){			
			if( (startPos+itemHeight) > viewPortHeight )
			{
				offset += viewPortHeight - (startPos+itemHeight);
			}
			if( itemHeight < viewPortHeight){
				var nOffset = offset - (viewPortHeight - itemHeight)/2;
				if(nOffset > startPos){
					offset = nOffset;
				}
			}
		}
		var hMax = getHeightMax();
		if(offset > hMax ){
			offset = hMax;
		}
		
		if(offset < startPos){
			offset = startPos;
		}
		
		$(name).animate({'top' : offset + "px"},{duration:500, queue:false});
	});
},

highlightPreview : function(){
	
	var rel = {
		'companyName' : 'companyNamePrev',
		'logoUpload'  : 'logoPrev',
		'companyWebsite' : 'companyWebsitePrev',
		'companyWebsite1': 'companyWebsitePrev',
		'companyWebsite2': 'companyWebsitePrev',
		'keywords-1-name' :  'companyKeywordsPrev',
		'keywords-2-name' :  'companyKeywordsPrev',
		'keywords-3-name' :  'companyKeywordsPrev',
		'keywords-4-name' :  'companyKeywordsPrev',
		'keywords-5-name' :  'companyKeywordsPrev'
	};
	
	function appendPreviewEvent(k, rel){
		var o = itemsCache[rel[k]] ? itemsCache[rel[k]] :  (itemsCache[rel[k]] = $('#'+ rel[k]));
		$('#'+ k).click(function(event){
			event.stopPropagation();
		})
		.focus(function(event){			
			o.addClass('highlight');			
		})
		.blur(function(event){
			o.removeClass('highlight');
		});
	}
	
	for(k in rel){
		appendPreviewEvent(k, rel);
	}	
},

formValidate : function(elems, fieldsRules){

	formData = {};
	formErrors = {};
	formFieldStorage = {};
	
	var isValid = true;
	$.each(elems, function(i, el){
		var v = $.trim(el.value), err = [], len = v.length;
		if(fieldsRules[el.name]){
			var rules = fieldsRules[el.name];
			if(rules['required'])
			{
				if( !v || !len || (rules['defaultValue'] && rules['defaultValue'] == v) ){
					err.push('required');
				}
			}
			if(!err.length){
				for(k in rules){
					switch(k){
						case 'not_null':
							if(v == 0 || v == "0")
							{
								err.push('not_null');
							}
						break;
						case 'minlen':
							if(len < rules['minlen'])
							{
								err.push('minlen');
							}
						break;
						case 'maxlen':
							if(len > rules['maxlen'])
							{
								err.push('maxlen');
							}
						break;
						case 'email_format':
							if( !v.match(/^([a-z0-9\-\_\.&])+@([a-z0-9\-\_\.&])+\.(([a-z]{2,4})|travel|museum)$/gi) ){
								err.push('email_format');
							};
						break;
						case 'website':
							if( !v.match(/https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?/) ){
								err.push('website');
							};
							break;
						case 'phone_number':
							if( /([^ 0-9\/\.-]+)/.test(v) ){
								err.push('phone_number');
							}
						break;						
					}
				}
			}	
			
			if(err.length){
				isValid = false;
				formErrors[el.name] = err;
			}
		}
		
		formData[el.name] = v;
		formFieldStorage[el.name] = $(this);
	});
	
  return {
  	'isValid'		  : isValid,
  	'formErrors'	  : formErrors,
  	'formData'		  : formData,
  	'formFieldStorage': formFieldStorage
  };
  
},

ajaxRequest : function(config){
	var ajaxConfig = {
		url: '/ajax/homeregister',
		dataType: 'json',
		type: 'POST',
		success: function(data){				
			try{
				if(!data.success && data.messages){
					for(k in data.messages){
						_msk.assignErrors( $('#'+ k), data.messages[k] );
					}
					return false;
				}
				document.location.href = _epo_links[$(formIdQuery + ' [name=package_name]').val() + '_option'];				
			}finally{
				_request = false;
			}
		},
		error: function(req, status, error){
		  _request = false;
		}
	};
	$.ajax($.extend({}, ajaxConfig, config));
},

dump: function(obj){
	for(k in obj){
		alert(k + ':' + obj[k]);
	}
}

};

})();



/**
 * jQuery.ScrollTo
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 *
 * @projectDescription Easy element scrolling using jQuery.
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 * Works with jQuery +1.2.6. Tested on FF 2/3, IE 6/7/8, Opera 9.5/6, Safari 3, Chrome 1 on WinXP.
 *
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * @id jQuery.scrollTo
 * @id jQuery.fn.scrollTo
 * @param {String, Number, DOMElement, jQuery, Object} target Where to scroll the matched elements.
 *	  The different options for target are:
 *		- A number position (will be applied to all axes).
 *		- A string position ('44', '100px', '+=90', etc ) will be applied to all axes
 *		- A jQuery/DOM element ( logically, child of the element to scroll )
 *		- A string selector, that will be relative to the element to scroll ( 'li:eq(2)', etc )
 *		- A hash { top:x, left:y }, x and y can be any kind of number/string like above.
*		- A percentage of the container's dimension/s, for example: 50% to go to the middle.
 *		- The string 'max' for go-to-end. 
 * @param {Number} duration The OVERALL length of the animation, this argument can be the settings object instead.
 * @param {Object,Function} settings Optional set of settings or the onAfter callback.
 *	 @option {String} axis Which axis must be scrolled, use 'x', 'y', 'xy' or 'yx'.
 *	 @option {Number} duration The OVERALL length of the animation.
 *	 @option {String} easing The easing method for the animation.
 *	 @option {Boolean} margin If true, the margin of the target element will be deducted from the final position.
 *	 @option {Object, Number} offset Add/deduct from the end position. One number for both axes or { top:x, left:y }.
 *	 @option {Object, Number} over Add/deduct the height/width multiplied by 'over', can be { top:x, left:y } when using both axes.
 *	 @option {Boolean} queue If true, and both axis are given, the 2nd axis will only be animated after the first one ends.
 *	 @option {Function} onAfter Function to be called after the scrolling ends. 
 *	 @option {Function} onAfterFirst If queuing is activated, this function will be called after the first scrolling ends.
 * @return {jQuery} Returns the same jQuery object, for chaining.
 *
 * @desc Scroll to a fixed position
 * @example $('div').scrollTo( 340 );
 *
 * @desc Scroll relatively to the actual position
 * @example $('div').scrollTo( '+=340px', { axis:'y' } );
 *
 * @dec Scroll using a selector (relative to the scrolled element)
 * @example $('div').scrollTo( 'p.paragraph:eq(2)', 500, { easing:'swing', queue:true, axis:'xy' } );
 *
 * @ Scroll to a DOM element (same for jQuery object)
 * @example var second_child = document.getElementById('container').firstChild.nextSibling;
 *			$('#container').scrollTo( second_child, { duration:500, axis:'x', onAfter:function(){
 *				alert('scrolled!!');																   
 *			}});
 *
 * @desc Scroll on both axes, to different values
 * @example $('div').scrollTo( { top: 300, left:'+=200' }, { axis:'xy', offset:-20 } );
 */
;(function( $ ){
	
	var $scrollTo = $.scrollTo = function( target, duration, settings ){
		$(window).scrollTo( target, duration, settings );
	};

	$scrollTo.defaults = {
		axis:'xy',
		duration: parseFloat($.fn.jquery) >= 1.3 ? 0 : 1
	};

	// Returns the element that needs to be animated to scroll the window.
	// Kept for backwards compatibility (specially for localScroll & serialScroll)
	$scrollTo.window = function( scope ){
		return $(window)._scrollable();
	};

	// Hack, hack, hack :)
	// Returns the real elements to scroll (supports window/iframes, documents and regular nodes)
	$.fn._scrollable = function(){
		return this.map(function(){
			var elem = this,
				isWin = !elem.nodeName || $.inArray( elem.nodeName.toLowerCase(), ['iframe','#document','html','body'] ) != -1;

				if( !isWin )
					return elem;

			var doc = (elem.contentWindow || elem).document || elem.ownerDocument || elem;
			
			return $.browser.safari || doc.compatMode == 'BackCompat' ?
				doc.body : 
				doc.documentElement;
		});
	};

	$.fn.scrollTo = function( target, duration, settings ){
		if( typeof duration == 'object' ){
			settings = duration;
			duration = 0;
		}
		if( typeof settings == 'function' )
			settings = { onAfter:settings };
			
		if( target == 'max' )
			target = 9e9;
			
		settings = $.extend( {}, $scrollTo.defaults, settings );
		// Speed is still recognized for backwards compatibility
		duration = duration || settings.speed || settings.duration;
		// Make sure the settings are given right
		settings.queue = settings.queue && settings.axis.length > 1;
		
		if( settings.queue )
			// Let's keep the overall duration
			duration /= 2;
		settings.offset = both( settings.offset );
		settings.over = both( settings.over );

		return this._scrollable().each(function(){
			var elem = this,
				$elem = $(elem),
				targ = target, toff, attr = {},
				win = $elem.is('html,body');

			switch( typeof targ ){
				// A number will pass the regex
				case 'number':
				case 'string':
					if( /^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(targ) ){
						targ = both( targ );
						// We are done
						break;
					}
					// Relative selector, no break!
					targ = $(targ,this);
				case 'object':
					// DOMElement / jQuery
					if( targ.is || targ.style )
						// Get the real position of the target 
						toff = (targ = $(targ)).offset();
			}
			$.each( settings.axis.split(''), function( i, axis ){
				var Pos	= axis == 'x' ? 'Left' : 'Top',
					pos = Pos.toLowerCase(),
					key = 'scroll' + Pos,
					old = elem[key],
					max = $scrollTo.max(elem, axis);

				if( toff ){// jQuery / DOMElement
					attr[key] = toff[pos] + ( win ? 0 : old - $elem.offset()[pos] );

					// If it's a dom element, reduce the margin
					if( settings.margin ){
						attr[key] -= parseInt(targ.css('margin'+Pos)) || 0;
						attr[key] -= parseInt(targ.css('border'+Pos+'Width')) || 0;
					}
					
					attr[key] += settings.offset[pos] || 0;
					
					if( settings.over[pos] )
						// Scroll to a fraction of its width/height
						attr[key] += targ[axis=='x'?'width':'height']() * settings.over[pos];
				}else{ 
					var val = targ[pos];
					// Handle percentage values
					attr[key] = val.slice && val.slice(-1) == '%' ? 
						parseFloat(val) / 100 * max
						: val;
				}

				// Number or 'number'
				if( /^\d+$/.test(attr[key]) )
					// Check the limits
					attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max );

				// Queueing axes
				if( !i && settings.queue ){
					// Don't waste time animating, if there's no need.
					if( old != attr[key] )
						// Intermediate animation
						animate( settings.onAfterFirst );
					// Don't animate this axis again in the next iteration.
					delete attr[key];
				}
			});

			animate( settings.onAfter );			

			function animate( callback ){
				$elem.animate( attr, duration, settings.easing, callback && function(){
					callback.call(this, target, settings);
				});
			};

		}).end();
	};
	
	// Max scrolling position, works on quirks mode
	// It only fails (not too badly) on IE, quirks mode.
	$scrollTo.max = function( elem, axis ){
		var Dim = axis == 'x' ? 'Width' : 'Height',
			scroll = 'scroll'+Dim;
		
		if( !$(elem).is('html,body') )
			return elem[scroll] - $(elem)[Dim.toLowerCase()]();
		
		var size = 'client' + Dim,
			html = elem.ownerDocument.documentElement,
			body = elem.ownerDocument.body;

		return Math.max( html[scroll], body[scroll] ) 
			 - Math.min( html[size]  , body[size]   );
			
	};

	function both( val ){
		return typeof val == 'object' ? val : { top:val, left:val };
	};

})( jQuery );