jQuery.fn.toggleHtml = function(value1, value2){
	if(this.html() == value1) {
		this.html(value2); 
	} else {
		this.html(value1);
	}
	
	return this;
}

jQuery.fn.toggleText = function(value1, value2){
	if(this.text() == value1) {
		this.text(value2); 
	} else {
		this.text(value1);
	}
	
	return this;
}

jQuery.fn.toggleValue = function(value1, value2){
	if(this.val() == value1) {
		this.val(value2); 
	} else {
		this.val(value1);
	}
	
	return this;
}

/**
 * Simple template
 * "The {adjective} {color} {animal} jumps".template({adjective: 'quick', color: 'brown', animal: 'fox'}) 
 * 
 * @author weepy
 * @param o
 * @return
 */
String.prototype.template = function (o) {
    return this.replace(/{([^{}]*)}/g,
        function (a, b) {
            var r = o[b];
            return typeof r === 'string' || typeof r === 'number' ? r : a;
        }
    );
};

function olength(o){
	var num = 0;
	for(var prop in o){
		num++;
	}
	return num;
}

jQuery.fn.resetPosition = function(smooth){
	if(!smooth){
		this.css({'position': 'relative', 'left': '0px', 'top': '0px'});
	} else {
		this.animate({'left': '0px', 'top': '0px'}, 'fast', 'linear', function(){
			$(this).css({'position': 'relative'});
		});
	}
}

jQuery.fn.tagName = function() {
	if(!this.length) return '';
    return this.get(0).tagName.toLowerCase();
}

jQuery.fn.disable = function(){
	if(this.tagName() == 'form'){
		$inputs = $(':input', this);
		$inputs.each(function(){
			if($(this).attr('disabled')) {
				$(this).data('disabled', 1);
			} else {
				$(this).attr('disabled', 'disabled');
			}
		});
	} else {
		this.attr('disabled', 'disabled');
	}
}

jQuery.fn.enable = function(){
	if(this.tagName() == 'form'){
		$inputs = $(':input', this);
		$inputs.each(function(){
			if(!$(this).data('disabled')) {
				$(this).removeAttr('disabled', 'disabled');
			}
		});
	} else {
		this.removeAttr('disabled', 'disabled');
	}
}

jQuery.fn.indexOf = function(e){
	for( var i=0; i<this.length; i++ ){
		if( this[i] == e ) return i;
	}
	return -1;
};

jQuery.fn.highlight = function(c, b){
	var color = c ? c : '#ffffa9';
	var backColor = b ? b : '#ffffff';
	this.animate({backgroundColor: color}, 'fast').animate({backgroundColor: backColor}, 1000);
}

/* Tourdeforce special */

var Discount = {
	value: 0,
		
	applyToValue: function(amount){
		if(this.value){
			amount = Math.ceil(amount * (100 - this.value) / 100);
		}
		return amount;
	}

};

/* Animate colors */
(function(jQuery){jQuery.each(['backgroundColor','borderBottomColor','borderLeftColor','borderRightColor','borderTopColor','color','outlineColor'],function(i,attr){jQuery.fx.step[attr]=function(fx){if(fx.state==0){fx.start=getColor(fx.elem,attr);fx.end=getRGB(fx.end)}fx.elem.style[attr]="rgb("+[Math.max(Math.min(parseInt((fx.pos*(fx.end[0]-fx.start[0]))+fx.start[0]),255),0),Math.max(Math.min(parseInt((fx.pos*(fx.end[1]-fx.start[1]))+fx.start[1]),255),0),Math.max(Math.min(parseInt((fx.pos*(fx.end[2]-fx.start[2]))+fx.start[2]),255),0)].join(",")+")"}});function getRGB(color){var result;if(color&&color.constructor==Array&&color.length==3)return color;if(result=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))return[parseInt(result[1]),parseInt(result[2]),parseInt(result[3])];if(result=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))return[parseFloat(result[1])*2.55,parseFloat(result[2])*2.55,parseFloat(result[3])*2.55];if(result=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))return[parseInt(result[1],16),parseInt(result[2],16),parseInt(result[3],16)];if(result=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))return[parseInt(result[1]+result[1],16),parseInt(result[2]+result[2],16),parseInt(result[3]+result[3],16)];if(result=/rgba\(0, 0, 0, 0\)/.exec(color))return colors['transparent'];return colors[jQuery.trim(color).toLowerCase()]}function getColor(elem,attr){var color;do{color=jQuery.curCSS(elem,attr);if(color!=''&&color!='transparent'||jQuery.nodeName(elem,"body"))break;attr="backgroundColor"}while(elem=elem.parentNode);return getRGB(color)}})(jQuery);
jQuery.cookie=function(name,value,options){if(typeof value!='undefined'){options=options||{};if(value===null){value='';options=$.extend({},options);options.expires=-1}var expires='';if(options.expires&&(typeof options.expires=='number'||options.expires.toUTCString)){var date;if(typeof options.expires=='number'){date=new Date();date.setTime(date.getTime()+(options.expires*24*60*60*1000))}else{date=options.expires}expires='; expires='+date.toUTCString()}var path=options.path?'; path='+(options.path):'';var domain=options.domain?'; domain='+(options.domain):'';var secure=options.secure?'; secure':'';document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join('')}else{var cookieValue=null;if(document.cookie&&document.cookie!=''){var cookies=document.cookie.split(';');for(var i=0;i<cookies.length;i++){var cookie=jQuery.trim(cookies[i]);if(cookie.substring(0,name.length+1)==(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break}}}return cookieValue}};
jQuery.location_hash = function(value){
	if(typeof value != 'undefined'){
		window.location.hash = '#' + value;
	} else {
		var hash = window.location.hash.substring(1);
		return hash;
	}
}

function html_select_date(id){
	this.id = id;
	selects = {};
	this.holder = $('#' + id);
	$('select', this.holder).each(function(){
		var $select = $(this);
		var id_parts = $select.attr('name').split('_');
		var type = id_parts[id_parts.length - 1].toLowerCase();
		selects[type] = $select;
	});
	this.selects = selects;
	
	this.val_day = function(){
		var day = this.selects['day'].val();
		if(day.length == 1) day = '0' + day;
		return day;
	};
	
	this.val_month = function(){
		var month = this.selects['month'].val();
		if(month.length == 1) month = '0' + month;
		return month;
	};
	
	this.val_year = function(){
		return this.selects['year'].val();
	};
	
	this.val = function(){
		if(this.isComplete()){
			return this.format();
		} else {
			return '';
		}
	};
	
	this.format = function(){
		return this.val_month() + '/' + this.val_day() + '/' + this.val_year();
	};
	
	this.isComplete = function(){
		return Boolean(this.val_day() && this.val_month() && this.val_year());
	};
	
	this.setError = function(on, force){
		if(on){
			for(sel in this.selects){
				$select = this.selects[sel];
				if(!$select.val() || isNaN($select.val()) || force){
					$select.addClass('error');
				}
			};
		} else {
			for(sel in this.selects){
				$select = this.selects[sel];
				$select.removeClass('error');
			};
		}
		return this;
	};
};

function validate_email(email) {
	   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,6})$/;
	   return reg.test(email);
	}

$.fn.center = function (absolute) {
	return this.each(function () {
		var t = $(this);
		
		t.css({
			position:	absolute ? 'absolute' : 'fixed', 
			left:		'50%', 
			top:		'50%', 
			zIndex:		'10003'
		}).css({
			marginLeft:	'-' + (t.width() / 2) + 'px', 
			marginTop:	'-' + (t.height() / 2) + 'px'
		});

		if (absolute) {
			t.css({
				marginTop:	parseInt(t.css('marginTop'), 10) + jQuery(window).scrollTop(), 
				marginLeft:	parseInt(t.css('marginLeft'), 10) + jQuery(window).scrollLeft()
			});
		}
	});
};

jQuery.fn.serializeFields = function(){
	var $field = null;
	var $form = $(this);
	var fields = $form.find('input:text,select,textarea, input[type=hidden]');
	var result = {};
	fields.each(function(){
		$input = $(this);
		result[$input.attr('name')] = $input.val();
	});
	
	$radios = $(this).find('input[type=radio]');
	$radios.each(function(){
		$radio = $(this);
		name = $radio.attr('name');
		result[name] = $form.find('input[type=radio][name=' + name + ']:checked').val();
	});
	 
	return result;
};

/**
* Нахождение цены в зависимости от количества человек
* @param prices
* @param number
* @return
*/
function getPriceOnNumber(prices, number){
	var price = 0;
	var fullPrices = [];
	$.each(prices, function(){
		fullPrices[this.number_begin] = this.price;
		if(this.number_end){
			for(var i = 0; i<this.number_end - this.number_begin; i++){
				fullPrices.push(this.price);
			}
		}
	});
	price = (number < fullPrices.length) ? parseInt(fullPrices[number]) : parseInt(fullPrices.pop());
	return price;
}

Array.prototype.without = function(value){
	var result = $.grep(this, function(n){
		return n != value;
	});
	return result;
}

function bind(obj, fun, args) {
	  return function() {
	    if (obj === true)
	      obj = this;
	    var f = typeof fun === "string" ? obj[fun] : fun;

	    return f.apply(obj, Array.prototype.slice.call(args || [])
	        .concat(Array.prototype.slice.call(arguments)));
	  };
	}


function stripTags(originalText, removeLinebreaks) {
    // Remove tags from the pasted stuff
    originalText = originalText.replace(/(<[^<>]*>)/g, "");
    // Remove newline characters, if we want to.
    if (removeLinebreaks) {
        originalText = originalText.replace(/\n/g, "");
    }

    return originalText;
}
