$.extend({
	delegate: function(fn, thisObject) {
      var parameters = Array.prototype.slice.call(arguments).slice(2);
 
      return function() {
         return fn.apply(thisObject || this, parameters.concat(Array.prototype.slice.call(arguments)));
      };
	}

});

$.widget('ui.news', {

	_init: function() {
   	this.element.find('.news-buttons .previous, .news-buttons .next').unbind().bind('click', this, function(event) {
      	event.data.change(($(this).hasClass('previous') ? '-1' : '1'));
      });
      
      if (this._getData('data') == null) {
      	var data = [];
         
         this.element.find('.news li').each(function() {
         	data.push($(this).html());
         });

      	this._setData('data', data);
      }
      
      this.element.find('.news').html('');

      this._setData('speed', 400);
		this._setData('disabled', false);
      this.change(1);
   },
   
   
   play: function() {
   	this.pause();
   	this.interval = setInterval($.delegate(this.change, this, '1'), 4000);
   },


   pause: function() {
   	if (this.interval == null) return;
   	clearInterval(this.interval);
      this.interval = null;
   },

   
   change: function(offset) {
   	if (this._getData('disabled')) return;
		
		var data = this._getData('data');
		var index = Number(this._getData('index'));

		switch (offset) {
			case '-1': index = (index == 1 ? data.length : index - 1); break;
			case '1': index = (index == data.length ? 1 : index + 1); break;
			default: index = offset;	
		}

		if (index == this._getData('index')) return;

		this.element.find('.control ul li a').removeClass('active').eq(index - 1).addClass('active');
		this._setData('index', index);
		this._setData('disabled', true);
		this.fade();
   },
   
   
   fade: function() {
   	var $this = this;
   	var value = this._getData('data')[this._getData('index') - 1];
      var $parent = this.element.find('.news');
      var speed = this._getData('speed');

      if ($parent.html().length > 0) {
      	$parent.find('li').fadeTo(speed, 0, function() {
            $parent.html('');
            $this.fade();
         });
      }
      else {
      	$parent.append("<li>" + value + "</li>");

         $parent.find('li').fadeTo(0, 0).fadeTo(speed, 1, function() {
            $this._setData('disabled', false);
            $this.play();
         });
      }
   }
   
});

$.widget('ui.button', {
			
	_init: function(options) {
		this.element.mouseover($.proxy(this.over, this));
		this.element.mouseout($.proxy(this.out, this));
	},
	
	
	fade: function(create) {
		if (create) {
			if (this.clone == null) {
				this.element.append(this.element.html());
				this.clone = this.element.find('> *:last');
				this.clone.addClass('over');
				this.clone.fadeTo(0, 0);
			}
			
			this.clone.stop(true);
			this.clone.fadeTo(500, 1);
		}
		else {
			if (this.clone != null) {
				this.clone.fadeTo(500, 0, $.proxy(this.remove, this));
			}
		}
	},
	
	
	remove: function() {
		if (this.clone != null) {
			this.clone.remove();
		}
		
		this.clone = null;
	},
	
	
	over: function() {
		if (this._status) return;
		this.fade(true);
	},
	
	
	out: function() {
		if (this._status) return;
		this.fade(false);	
	},
	
	
	status: function(status) {
		this._status = status
		this.element.css('cursor', (status ? 'default' : 'pointer'));
		this.fade(status);
	}

});


$.scale = function(width, height, originalWidth, originalHeight) {
	var size;

	size = new Object();
	size.width = originalWidth;
	size.height = originalHeight;

	var xScale = width / originalWidth;
	var yScale = height / originalHeight;
	var scale = (xScale > yScale) ? yScale : xScale;

	if (scale < 1) {
		size.width *= scale;
		size.height *= scale;
	}
	
	size.width = Math.round(size.width);
	size.height = Math.round(size.height);

	return size;
}


$.widget('ui.gallery', {

	_init: function() {
		var $this = this;

		if ($.browser.msie && $.browser.version < 7) {
			$(window).scroll(function() {
				$this.element.css('top', $(window).scrollTop() + 'px');		  
			});
		}
		else {
			this.element.css('position', 'fixed');	
		}
		
		this.element.find('.close').unbind().click($.delegate(this.hide, this));
	},


	update: function(id, index) {
		var $this = this;
		var data = $('#' + id).val();
		var images = $('#' + id).find('img');
		//var images = $("<div>" + data + "</div>").find('img');
		var image;
		var $element;
		var html = "";
		
		if (isNaN(index)) index = 1;
		
		index = Math.max(1, Math.min(images.length, index));

		for (var i = 0; i < images.length; i++) {
			image = images.eq(i);
			html += "<li" + (i + 1== images.length ? " class=\"last\"" : "") + "><a href=\"javascript:void(0)\" rel=\"" + (i + 1) + "\"><span><em></em><img src=\"" + image.attr('alt') + "\" /></span></a></li>";
		}

		$element = this.element.find('.thumbnails .items ul');
		$element.html(html);
		$element.css('width', Math.max(0, ((images.length * 97) - 13)) + 'px');
		$element.find('li a img').hide().load(function() {
			$(this).css('margin-left', Math.round((84 - $(this).width()) / 2) + 'px');
			$(this).show();
		});

		$element = this.element.find('.image .info');

		if (!$.browser.msie) {
			$element.show();
			$element.fadeTo(0, 0);
		}

		this.element.find('.image').unbind().hover(
			function() {
				var $element = $(this).find('.info');
				($.browser.msie ? $element.show() : $element.animate({ opacity: 1 }, 500)); 
			},
			function() {
				var $element = $(this).find('.info');
				($.browser.msie ? $element.hide() : $element.animate({ opacity: 0 }, 500));
			}
		);
		this.element.find('.image .info .button1, .image .info .button2').unbind().click(function() {
         $this.change(($(this).hasClass('button1') ? '-1' : '1'));
      });
		this.element.find('.thumbnails .items ul li a').unbind().click(function() {
			$this.change(parseInt($(this).attr('rel'), 10));	
		}).button();

		var limit = 7;
		var pageCount = Math.ceil(images.length / limit);

		this._setData('index', null);
		this._setData('limit', limit);
		this._setData('data', images);
		this._setData('pageCount', pageCount);
		
		html = "";
		
		for (var i = 0; i < pageCount; i++)
		{
			html += "<li><a href=\"javascript:void(0)\" rel=\"" + (i + 1) + "\"" + (i == 0 ? " class=\"active\"" : "") + "></a></li>";
		}

		this.element.find('.pagination ul').html(html);

		this.element.find('.pagination ul li a').unbind().click(function() {
         $this.slide(parseInt($(this).attr('rel'), 10));
      });
		this.element.find('.pagination .button1, .pagination .button2').unbind().click(function() {
         $this.slide(($(this).hasClass('button1') ? '-1' : '1'));
      });
		
		this.element.find('.overlay').unbind().click(function() { $this.hide(); });
		this.element.find('.image img').remove();
		
		this._setData('enabled', true);
		this.element.show();

		if ($.browser.msie && $.browser.version < 7) {
			$(window).resize(function() {
				$this.element.find('.overlay').height($(this).height()); 
			});
			$(window).trigger('resize');
			
			this.element.find('.content').show();
			this.element.find('.overlay').show();
			this.change(index);
		}
		else
		{
			$element = this.element.find('.overlay');
			$element.fadeTo(0, 0);
			$element.fadeTo(500, 0.75);
			$element = this.element.find('.content');
			$element.fadeTo(0, 0);
			$element.fadeTo(500, 1, function() {
				$this.change(index);						 
			});
		}
	},
	
	
	hide: function() {
		var $this = this;

		if ($.browser.msie && $.browser.version < 7) {
			this.element.find('.content').hide();
			this.element.find('.overlay').hide();
			this.element.hide();
		}
		else {
			this.element.find('.overlay').fadeTo(500, 0);
			this.element.find('.content').fadeTo(500, 0, function() {
				$this.element.hide();
			});
		}
	},

	
	change: function(offset) {
		var $this = this;
		var data = this._getData('data');
		var $parent;
		var $images;
		var $image;
		var $button;

		 switch (offset) {
      	case '-1': index = (index == 1 ? data.length : index - 1); break;
         case '1': index = (index == data.length ? 1 : index + 1); break;
			default: index = offset;
      }

      if (index == this._getData('index')) return;
		
		data = data.eq(index - 1);

		this._setData('index', index);

		$parent = this.element.find('.image .info .description');
		$parent.find('p').html(data.attr('title'));

		if (data.attr('title').length > 0) {
			$parent.show();
			$parent.find('div').fadeTo(1, 0.75);
		}
		else {
			$parent.hide();
			$parent.find('div').fadeTo(0, 0);
		}

		this.element.find('.thumbnails .items ul li a').removeClass('active').button('status', false);
		
		$button = this.element.find('.thumbnails .items ul li a[rel=' + index + ']');
		$button.addClass('active').button('status', true);
		$button.find('img').each(function() {
			var $border;
			var width = $(this).width();
			var height = $(this).height();
			
			$border = $(this).parent().find('em');
			$border.css('width', (width - 6) + 'px');
			$border.css('height', (height - 6) + 'px');
			$border.css('margin-left', Math.floor(7) + 'px');
			$border.css('margin-top', Math.floor(0) + 'px');
		});
		
		if (!$.browser.msie) $button.find('em').fadeTo(0, 0).fadeTo(500, 1);

		$parent = this.element.find('.image');
		$parent.find('img').remove();
		$parent.append("<div class=\"file\"><img src=\"" + data.attr('src') + "\" /></div>");
		$image = $parent.find('img:last');
		$image.click($.delegate(this.change, this, '1'));
		$image.fadeTo(0, 0);
		$image.parent().fadeTo(0, 0);
		$image.load(function() {
			var size = $.scale(666, 443, $(this).width(), $(this).height());

			$image.fadeTo(0, 1);
			$image.css('width', size.width + 'px');
			$image.css('height', size.height + 'px');
			$image.css('margin-top', Math.round((443 - size.height) / 2) + 'px');
			$image.css('margin-left', Math.round((666 - size.width) / 2) + 'px');
			$image.parent().fadeTo(1000, 1);
		});

		this.slide(Math.floor((index - 1) / this._getData('limit')) + 1);
		this.element.find('.pagination .status').html("Image " + index + " of " + this._getData('data').length);
	},


	slide: function(offset)
   {
   	var $this = this;
   	var index = this._getData('page');
      var items = this.element.find('.thumbnails .items ul li');
      var item = items.eq(0);
      var length = item.width();
      var spacing = parseInt(item.css('marginRight'), 10);
		var count = Math.floor((this.element.find('.items').width() + spacing) / (length + spacing));
      var total = Math.ceil(items.length / count);
      var data = {};

      switch (offset) {
      	case '-1': index = (index == 1 ? total : index - 1); break;
         case '1': index = (index == total ? 1 : index + 1); break;
			default: index = offset;
      }
 
      data.marginLeft = -((length + spacing) * count) * (index - 1);

      this._setData('page', index);
      this.element.find('.thumbnails .items ul').stop(true).animate(data, 1000);
		this.element.find('.pagination ul li a').removeClass('active');
		this.element.find('.pagination ul li a[rel=' + index + ']').addClass('active');
   }

});

$.widget('ui.validate', {

	_init: function() {
   	var $this = this;
   
		this.element.filter('form').submit(function() {
			return $this.validate();										  
		});
      
      this.update();
      
      var $fields = this.fields();
      
      for (var $i = 0; $i < $fields.length; $i++) {
      	$fields.eq($i).trigger('blur');
      }
	},

   update: function() {
   	var $this = this;
      var $fields, $field;
   
   	$fields = this.fields();

		for (var $i = 0; $i < $fields.length; $i++) {
			$field = $fields.eq($i);
         $field.data('validator', this);
			if ($field.data('type') == null) {
         	$field.data('type', $field.attr('type'));
 				$field.unbind();
            $field.focus(function() {
               if ($(this).val() == $(this).attr('title')) {
                  $(this).val('');
                  $this.clone($(this), true);
               }
            });
            $field.blur(function() {
               if ($(this).val().length == 0) {
                  $(this).val($(this).attr('title'));
                  $this.clone($(this), false);
               }
            });
         }
		}
   },

	fields: function() {
		return this.element.find('input, textarea, select');
	},

	clone: function($field, password) {
		var type = $field.data('type');
      var attributes = ['id', 'class', 'style', 'type', 'title', 'name', 'value'];
      var attribute;
      var html;
      var $clone;
      
      if ($field.attr('type') == (password ? 'password' : 'text')) return;

		if (type == 'password') {
         html = "<input type=\"" + (password ? 'password' : 'text') + "\"";
 
         for (var i = 0; i < attributes.length; i++)
         {
         	attribute = $field.attr(attributes[i]);

            if (attribute != null) {
            	html += attributes[i] + "=\"" + attribute + "\"";
            }
         }

         html += "></input>";
 
         $field.after(html);
         $clone = $field.next();
         $field.remove();
         this.update();
         $clone.data('type', type);
         if (password) $clone.focus();
		}
	},

	validate: function() {
		var $fields = this.fields();
      var $field;
      var values = {};
      var value;
      var parts, part;
      var valid;
		var result = true;
      var errors = {};
      var error;

		for ($i = 0; $i < $fields.length; $i++) {
			$field = $fields.eq($i);
         if ($field.data('validator') == this) {
            value = ($field.val() == $field.attr('title') ? '' : $field.val());
            parts = $field.attr('class').split(" ");
            part = null;
   
            for ($j = 0; $j < parts.length; $j++) {
               if (parts[$j].slice(0, 8) == 'validate') {
                  part = parts[$j].slice(9, -1).split(',');
                  break;	
               }
            }

            if (part != null) {
               switch (part[0]) {
                  case 'email': valid = jQuery.email(value); break;
                  default: valid = (value.length >= 1);
               }

               if ($field.is('input[type=text]')) error = 'input-text-error';
               else if ($field.is('input[type=password]')) error = 'input-text-error';
               else if ($field.is('textarea')) error = 'textarea-error';

               $field.parent().toggleClass(error, !valid);
               errors[$field.attr('name')] = !valid;
               values[$field.attr('name')] = value;
   
               if (!valid) result = false;
            }
         }
		}

		if (this._getData('submit') != null)
      {
      	this._getData('submit').apply(this.element[0], [result, errors, values]);
      	return false;
      }

		if (result) this.cleanup();
		return result;
	},
 
   cleanup: function() {
   	var $fields = this.fields();
      var $field;

      for (var i = 0; i < $fields.length; i++) {
         $field = $fields.eq(i);
         if ($field.val() == $field.attr('title')) $field.val('');
      }
   },
   
   submit: function() {
   	this.cleanup();
      this.element[0].submit();
   }

});

jQuery.fn.center = function () {
	if ($.browser.msie && $.browser.version < 7){
		this.css("position","absolute");
		this.css("top", "200px");
		this.css("left", ( $(window).width() - this.outerWidth() ) / 2 + "px");
	}else{
		this.css("position","fixed");
		this.css("top", ( $(window).height() - this.outerHeight() ) / 2 + "px");
		this.css("left", ( $(window).width() - this.outerWidth() ) / 2 + "px");
	}
    return this;
}

$.widget('ui.contactAccordeon', {

	_init: function() {
		var obj = this;
		var parent = this.element;
		
		parent.find('.contact-handle').click(function(){
			var el = $(this);
			obj.toggle(el);
		});
		
		parent.find('.location-down-content').each(function(){
			$(this).css('max-height',$(this).innerHeight());
			$(this).css('height','0px');
		});
		
	},
	
	toggle: function(el){
		if(el.next('.location-down-content').css('height') == '0px'){
			$('.location-down-content:visible').stop(true,true).animate({"height": "0px"}, "slow");
			var height = el.next('.location-down-content').css('max-height');
			el.next('.location-down-content').stop(true,true).animate({"height": height}, "slow");
			$('.contact-phones .location-down').removeClass('location-down');
			el.parent('li').addClass('location-down');
		}else{
			$('.location-down-content:visible').stop(true,true).animate({"height": "0px"}, "slow");
			$('.contact-phones .location-down').removeClass('location-down');
		}
	}
	
});

$.widget('ui.pinmap', {

	_init: function() {
		var popup = this.element.children('#map-lightbox');
		var obj = this;
		var parent = this.element;
				
		this.element.children('.pin').mouseover(function(){
			var loc = $(this).attr('rel');
			var top = parseInt($(this).css('top')) - 56;
			var left = parseInt($(this).css('left')) - 8;
			var content = $(this).html();
			popup.find('.pin-content').html(content);
			
			var link = '';
			if(loc == 'uk'){ link = '/contact-us/europe'; }
			if(loc == 'us'){ link = '/contact-us/north-america'; }
			if(loc == 'me'){ link = '/contact-us/middle-east'; }
			popup.find('.view-details').attr('href',link);
			
			popup.removeClass('fixed');
			
			$(this).addClass('active');
			obj.show(popup,top,left);
		});
		
		this.element.children('.pin').click(function(){
			popup.addClass('fixed');
		});
		
		popup.mouseover(function(){
			$(this).stop(true,true).show();
		});
		
		this.element.children('.pin, #map-lightbox').mouseout(function(){
			parent.children('.pin').removeClass('active');
			obj.hide(popup);
		});
		
		this.element.children('.overlay').click(function(){
			parent.children('.pin').removeClass('active');
			popup.hide();
		});
	},
	
	show: function(el,top,left){
		el.css({ 'top':top+'px', 'left':left+'px' });
		el.stop(true,true).show();
	},
	
	hide: function(el){
		if(el.hasClass('fixed')){
			return;
		}else{
			if(!$.browser.msie){
				el.stop(true,true).fadeOut(200);
			}else{
				el.hide();
			}
		}
	}
});

$.widget('ui.sstabs', {

	_init: function() {
		var obj = this;
		var parent = this.element;
		
		parent.find('.tabs a').click(function(){
			if(!$(this).hasClass('active')){
				parent.find('.tabs a.active').removeClass('active');
				$(this).addClass('active');
				var div = $(this).attr('rel');
				if(!$.browser.msie){
					$('.tab-content:visible').stop(true,true).fadeOut(function(){
						$('#'+div).fadeIn();
					});
				}else{
					$('.tab-content:visible').hide();
					$('#'+div).show();
				}
			}
		});
		parent.find('.tab-content .conic-link').click(function(){
			parent.find('.tabs .conic a').click();
		});
		parent.find('.tab-content .hypar-link').click(function(){
			parent.find('.tabs .hypar a').click();
		});
		parent.find('.tab-content .barrel-link').click(function(){
			parent.find('.tabs .barrel a').click();
		});
		
	}
});



$.widget('ui.frontSections', {

	_init: function() {
		var obj = this;
		var parent = this.element;
		
		parent.find('.section-link').hover(function(){
			if(!parent.hasClass('working') && !$(this).hasClass('active')){
				parent.find('.active').removeClass('active').addClass('inactive');
				$(this).removeClass('inactive');
				parent.addClass('working');
				var section = $(this).attr('rel');
				obj.toggle($('div'+section), $('img'+section));
				parent.removeClass('working');
				parent.find('.section-link.active').removeClass('active');
				$(this).addClass('active');
			}
		});
	},
	
	toggle: function(el, img){
		$('.main-header-container .main-header-image').parent().stop(true,true).fadeOut();
		img.parent().stop(true,true).fadeIn('1500');
	}
	
});

$.widget('ui.validation', {
	options: {
		validate: '',
		valtype: 'outline' //outline, inline
	},
	_create: function() {
		var obj = this;
		var parent = this.element;
		var items = parent.find('.validate');
		var validated = 0;
		var validate = this.options.validate;
		var valtype = this.options.valtype;
		
		items.blur(function(){
			validated = 0;
			validated = obj.validate($(this));
		});
		parent.submit(function(){
			items = parent.find('.validate');
			validated = 0;
			items.each(function(){
				if($(this).is(':visible')){
					validated += obj.validate($(this));
				}
			});
			if(validated != 0){
				parent.removeClass('validated');
				return false;
			}else{
				parent.addClass('validated');
				return true;
			}
		});
		
	},
	
	_init: function(){
		var obj = this;
		var validate = this.options.validate;
		var items = this.element.find('.validate');
		var validated = 0;
		var valtype = this.options.valtype;
		
		if(validate == 'validate'){
			validated = 0;
			items.each(function(){
				validated += obj.validate($(this));
			});
			if(validated != 0){
				this.element.removeClass('validated');
			}else{
				this.element.addClass('validated');
			}
		}
	},
	
	validate: function(el){
		var content = el.val();
		var emailregex = /^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$/;
		var creditregex = /^[0-9\-\s]+$/;
		var cvvregex = /^([0-9]{3,4})$/;
		var weightregex = /^([0-9]{2,3})$/;
		var passregex = /^([A-Za-z0-9]+)$/;
		var passlength = /^([A-Za-z0-9]{6,25})$/;
		var errors = 0;
		var error_msg = '';
		var valtype = this.options.valtype;
		
		if(el.hasClass('vldemail')){
			if(el.hasClass('vldrequired') || el.val().length > 0){
				if(el.val() != el.attr('title') || el.attr('title') == ''){
					if(content.search(emailregex) == -1){
						errors+=1;
						error_msg += '<li class="entry">A valid email is required</li>';
					}
				}
			}
		}
		if(el.hasClass('vldcredit')){
			if(el.hasClass('vldrequired') || el.val().length > 0){
				if(content.search(creditregex) == -1){
					errors+=1;
					error_msg += '<li class="entry">A valid credit card number is required</li>';
				}
			}
		}
		if(el.hasClass('vldcvv')){
			if(el.hasClass('vldrequired') || el.val().length > 0){
				if(content.search(cvvregex) == -1){
					errors+=1;
					error_msg += '<li class="entry">A valid CSV code is required</li>';
				}
			}
		}
		if(el.hasClass('vldweight')){
			if(el.hasClass('vldrequired') || el.val().length > 0){
				if(content.search(weightregex) == -1){
					errors+=1;
					error_msg += '<li class="entry">A valid weight is required</li>';
				}
			}
		}
		if(el.hasClass('vldpass')){
			if(el.hasClass('vldrequired') || el.val().length > 0){
				if(content.search(passregex) == -1){
					errors+=1;
					error_msg += '<li class="entry">A valid Password is required</li>';
				}
			}
		}
		if(el.hasClass('vldpasslength')){
			if(el.hasClass('vldrequired') && el.val().length > 0){
				if(content.search(passlength) == -1){
					errors+=1;
					error_msg += '<li class="entry">A minimum of 6 characters long</li>';
				}
			}
		}
		if(el.hasClass('vldrequired')){
			if(content.length == 0 || el.val() == el.attr('title')){
				if(el.val() == el.attr('title') || el.attr('title') == ''){
					errors+=1;
					error_msg += '<li class="entry">This field is required</li>';
				}
			}
			
			// Checkbox
			if( el.attr('type') == "checkbox" ) {
				if( !el.is(":checked") ) {
					errors+=1;
					error_msg += '<li class="entry">This field is required</li>';
				}
			}
		}
		el.next('.validation-msg').remove();
		
		var outerBorder = el.closest('.user-input-border');
		
		if((errors > 0 && !el.hasClass('hotel-input')) || (errors > 0 && el.hasClass('hotel-input') && $('input[name="cbox-hotel-transfer"]').is(':checked'))){
			el.addClass('error');
			
			if(valtype == 'outline'){
				if( $('.co-stages-pd').length > 0 ) {
					el.addClass('user-input-invalid');
					outerBorder.addClass('user-input-border-invalid');
				} else {
					el.parents('.bill-addr li').css({'position':'relative', 'z-index':'3'});
					el.parents('.deliv-addr li').css({'position':'relative', 'z-index':'2'});
					el.after('<div class="validation-msg"><ul class="list">'+ error_msg +'</ul><div class="validation-bottom"></div></div>');
					el.next('.validation-msg').show();
					el.next('.validation-msg').bind('mouseleave click',function(){
						if(!$.browser.msie){
							$(this).fadeOut(function(){
								$(this).remove();
							});
						}else{
							$(this).remove();
						}
					});
				}
			}
			if(valtype == 'inline'){
				el.parent().addClass('user-input-invalid');
			}
		
			return 1;
		}else{
			el.removeClass('error');
			el.removeClass('user-input-invalid');
			el.parent().removeClass('user-input-invalid');
			outerBorder.removeClass('user-input-border-invalid');
			return 0;
		}
		
	}
	
});

$.widget("ui.helperValue", {
	_create: function() {
		var obj = this;
		var parent = this.element;
		var form = parent.closest('form');

		if(parent.val() == ''){
			parent.val(parent.attr('title'));
		}

		parent.focus(function(){
			if($(this).val() == $(this).attr('title')){
				$(this).val('');
			}
		});

		parent.blur(function(){
			if($(this).val() == ''){
				$(this).val($(this).attr('title'));
			}
		});
	}
});

$.widget('ui.ajaxform', {
	options: {
		reqclass: '',
		type: 'POST'
	},
	
	_create: function() {
		var obj = this;
		var parent = this.element;
		var reqclass = this.options.reqclass;
		
		parent.submit(function(){
			if(reqclass.length > 0){
				if(parent.hasClass(reqclass)){
					obj.sendout();
				}
			}else{
				obj.sendout();
			}
			return false;
		});
	},
	
	sendout: function(){
		var formdata = this.element.serialize();
		var callback = this.options.change;
		var type = this.options.type;
		var address = this.options.address;
		
		$.ajax({
			type: type,
			url: address,
			data: formdata,
			success: function(data) {
				if ($.isFunction(callback)) callback(data); 
			}
		});
	}
	
});

$().ready(function() {

	$('.wrapper #inner-nav .dropdown').click(function(){
		$(this).parent().nextAll('li.drop').slideToggle();
		$(this).toggleClass('v-arrow');
	});

	$('.validate-form').validation();
	$('.helper-value').helperValue();

	//$('.main-header-container').prepend('<img class="main-header-image shade-section" src="/sites/all/themes/fabric/images/main-header.png" alt="Fabric Architecture" style="display:none;" /><img class="main-header-image signature-section" src="/sites/all/themes/fabric/images/main-header3.png" alt="Fabric Architecture" style="display:none;" /><img class="main-header-image interiors-section" src="/sites/all/themes/fabric/images/main-header4.png" alt="Fabric Architecture" style="display:none;" />');
	$('.main-header-container .site-sections').frontSections();

	$('.signature-tabs').sstabs();

	$('.country-dropdown-link').parent('.editing').hover(function(){
		$(this).children('.country-list').stop(true,true).slideToggle();
	});

	$('.contact-phones').contactAccordeon();
	$('.map-container').pinmap();
	
	$('.extra-information').hide();
	$('.read-more-link').click(function(){
		$('.extra-information').slideToggle();
	});
	$('#hide_extend').click(function(){
		$('.extra-information').slideToggle();
	});
	
	$('#gallery').gallery();
	
	$('.gallery-button').click(function() {
		$('#gallery').gallery('update', $(this).attr('rel'));
	});
	$('.thumb-back-1 .gallery-button2').click(function() {
		$('#gallery').gallery('update', $(this).attr('rel'), 2);
	});
	$('.thumb-back-2 .gallery-button2').click(function() {
		$('#gallery').gallery('update', $(this).attr('rel'), 3);
	});
	$('.thumb-back-3 .gallery-button2').click(function() {
		$('#gallery').gallery('update', $(this).attr('rel'), 4);
	});
	$('.thumb-back-4 .gallery-button2').click(function() {
		$('#gallery').gallery('update', $(this).attr('rel'), 5);
	});
	
	$('#careers-popup .close, #careers-popup-overlay').click(function() {
		$('#careers-popup').fadeOut('fast', function() {
			$('#careers-popup-overlay').fadeOut('slow'); 
		});
	});
	$('#recruiting-popup .close, #careers-popup-overlay').click(function() {
		$('#recruiting-popup').fadeOut('fast', function() {
			$('#careers-popup-overlay').fadeOut('slow'); 
		});
	});
	$('#whats-popup .close, #careers-popup-overlay').click(function() {
		$('#whats-popup').fadeOut('fast', function() {
			$('#careers-popup-overlay').fadeOut('slow'); 
		});
	});
	$('#brochure-popup .close, #brochure-popup-overlay, #brochure-popup .cancel').live('click',function() {
		$('#brochure-popup').fadeOut('fast', function() {
			$('#brochure-popup-overlay').fadeOut('slow'); 
		});
	});
	$('#video-popup .close, #video-popup-overlay').click(function() {
		$('#video-popup').fadeOut('fast', function() {
			$('#video-popup-overlay').fadeOut('slow'); 
		});
	});
	
	$('.specification').click(function() {
		$index = parseInt($(this).attr('rel'), 11);
		$data = $('#careers-popup-data').find('li').eq($index - 1).find('.lightbox-content').html();
		$popup = $('#careers-popup');
		$popup.find('.popup-middle').html($data);

		$i = 1;
		$popup.find('.navigation a').each(function() { this.index = $i; $i++; });
		$popup.find('.navigation a').click(function() {
				if ($(this).hasClass('apply')) return;
				$popup.find('.navigation a').removeClass('active');
				$(this).addClass('active');
				$items = $popup.find('.navigation-content-item');
				$items.hide();
				$items.eq(this.index - 1).fadeIn('slow');
		});
		
		$overlay = $('#careers-popup-overlay');
		$overlay.show();
		$overlay.fadeTo(0, 0);
		$overlay.fadeTo('fast', 0.8, function() {
			$popup.fadeIn('slow'); 
		});

		$(window).trigger('resize');
	});
	
	$('.contact-send-message').click(function() {
		$index = parseInt($(this).attr('rel'), 11);
		$data = $('#careers-popup-data').children('li').eq($index - 1).find('.lightbox-content').html();
		$popup = $('#careers-popup');
		$popup.find('.popup-middle').html($data);

		$i = 1;
		$popup.find('.navigation a').each(function() { this.index = $i; $i++; });
		$popup.find('.navigation a').click(function() {
				if ($(this).hasClass('apply')) return;
				$popup.find('.navigation a').removeClass('active');
				$(this).addClass('active');
				$items = $popup.find('.navigation-content-item');
				$items.hide();
				$items.eq(this.index - 1).fadeIn('slow');
		});
		
		$overlay = $('#careers-popup-overlay');
		$overlay.show();
		$overlay.fadeTo(0, 0);
		$overlay.fadeTo('fast', 0.8, function() {
			$popup.fadeIn('slow'); 
		});

		$(window).trigger('resize');
	});
	
	$('#top-nav .recruiting').click(function() {
		$index = parseInt($(this).attr('rel'), 11);
		$data = $('#recruiting-popup-data').children('li').eq($index - 1).find('.lightbox-content').html();
		
		$popup = $('#recruiting-popup');
		$popup.find('.popup-middle').html($data);

		$i = 1;
		$popup.find('.navigation a').each(function() { this.index = $i; $i++; });
		$popup.find('.navigation a').click(function() {
				if ($(this).hasClass('apply')) return;
				$popup.find('.navigation a').removeClass('active');
				$(this).addClass('active');
				$items = $popup.find('.navigation-content-item');
				$items.hide();
				$items.eq(this.index - 1).fadeIn('slow');
		});
		
		$overlay = $('#careers-popup-overlay');
		$overlay.show();
		$overlay.fadeTo(0, 0);
		$overlay.fadeTo('fast', 0.8, function() {
			if(!$.browser.msie){
				$popup.fadeIn('slow'); 
			}else{
				$popup.show(); 
			}
		});

		$(window).trigger('resize');
	});
	
	$('.whats-popup-button').click(function() {
		$index = parseInt($(this).attr('rel'));			
		$data = $('#whats-popup-data').children('li').eq($index - 1).find('.lightbox-content').html();
		$popuptwo = $('#whats-popup');
		$popuptwo.find('.whats-popup-middle').html($data);

		$i = 1;
		$popuptwo.find('.navigation a').each(function() { this.index = $i; $i++; });
		$popuptwo.find('.navigation a').click(function() {
				if ($(this).hasClass('apply')) return;
				$popuptwo.find('.navigation a').removeClass('active');
				$(this).addClass('active');
				$items = $popuptwo.find('.navigation-content-item');
				$items.hide();
				$items.eq(this.index - 1).fadeIn('slow');
		});
		
		$overlay = $('#careers-popup-overlay');
		$overlay.show();
		$overlay.fadeTo(0, 0);
		$overlay.fadeTo('fast', 0.8, function() {
			$popuptwo.fadeIn('slow'); 
		});

		$(window).trigger('resize');
		return false;
	});
	
	$('.brochure-popup-button').click(function() {
		$index = parseInt($(this).attr('rel'));
		var pdf = $(this).attr('href')
		$data = $('#brochure-popup-data').children('li').eq($index - 1).find('.lightbox-content').html();
		$popuptwo = $('#brochure-popup');
		$popuptwo.find('.brochure-popup-middle').html($data);
		$('#brochure-popup .brochure-popup-middle .brochure-download input[name="brochure"]').val( $(this).attr('title') );
		$popuptwo.find('.brochure-popup-middle form').attr('action', pdf);
		$('#brochure-popup .brochure-popup-middle form').submit(function(){
			$(this).removeClass('validated');
			$('#brochure-popup .brochure-popup-middle form').validation({ validate: 'validate' });
			if( $(this).hasClass('validated') ){
				$(this).removeClass('validated');

				$('#brochure-popup .brochure-request-form').fadeOut(function(){
					$('#brochure-popup .brochure-request-thankyou').fadeIn();

					var name = $('#brochure-popup .brochure-popup-middle .brochure-download input[name="name"]').val();
					var email = $('#brochure-popup .brochure-popup-middle .brochure-download input[name="email"]').val();
					var tel = $('#brochure-popup .brochure-popup-middle .brochure-download input[name="tel"]').val();
					var company = $('#brochure-popup .brochure-popup-middle .brochure-download input[name="company"]').val();
					var brochure = $('#brochure-popup .brochure-popup-middle .brochure-download input[name="brochure"]').val();

					$('#brochure-popup .brochure-popup-middle .brochure-download input[name="name"]').val('');
					$('#brochure-popup .brochure-popup-middle .brochure-download input[name="email"]').val('');
					$('#brochure-popup .brochure-popup-middle .brochure-download input[name="tel"]').val('');
					$('#brochure-popup .brochure-popup-middle .brochure-download input[name="company"]').val('');
					$('#brochure-popup .brochure-popup-middle .brochure-download input[name="brochure"]').val('');

					$.ajax({
						type: 'POST',
						url: 'http://www.fabricarchitecture.com/php/send-emails.php',
						data: 'brochuredownloaded=1&name='+name+'&email='+email+'&tel='+tel+'&company='+company+'&brochure='+brochure
					});

				});
			}
		});

		Cufon.set('fontSize', '30px').replace('#brochure-popup .brochure-popup-middle .title');
		Cufon.set('fontSize', '30px').replace('#brochure-popup .brochure-popup-middle .brochure-request-thankyou .thankyou');
		Cufon.set('fontSize', '15px').replace('#brochure-popup .brochure-popup-middle .brochure-request-thankyou .questions');

		$i = 1;
		$popuptwo.find('.navigation a').each(function() { this.index = $i; $i++; });
		$popuptwo.find('.navigation a').click(function() {
				if ($(this).hasClass('apply')) return;
				$popuptwo.find('.navigation a').removeClass('active');
				$(this).addClass('active');
				$items = $popuptwo.find('.navigation-content-item');
				$items.hide();
				$items.eq(this.index - 1).fadeIn('slow');
		});
		
		$overlay = $('#brochure-popup-overlay');
		$overlay.show();
		$overlay.fadeTo(0, 0);
		$overlay.fadeTo('fast', 0.8, function() {
			$popuptwo.fadeIn('slow'); 
		});

		$(window).trigger('resize');
		return false;
	});
	
	$('.video-popup-button').click(function() {
		$index = parseInt($(this).attr('rel'));			
		$data = $('#video-popup-data').children('li').eq($index - 1).find('.lightbox-content').html();
		$popupthree = $('#video-popup');
		$popupthree.find('.video-popup-middle').html($data);
		var pwidth = $('#video-popup-data').children('li').eq($index - 1).find('.lightbox-content').css('width');
		var pheight = $('#video-popup-data').children('li').eq($index - 1).find('.lightbox-content').css('height');
		
		$i = 1;
		$popupthree.find('.navigation a').each(function() { this.index = $i; $i++; });
		$popupthree.find('.navigation a').click(function() {
				if ($(this).hasClass('apply')) return;
				$popupthree.find('.navigation a').removeClass('active');
				$(this).addClass('active');
				$items = $popupthree.find('.navigation-content-item');
				$items.hide();
				$items.eq(this.index - 1).fadeIn('slow');
		});
		
		$overlay = $('#video-popup-overlay');
		$overlay.show();
		$overlay.fadeTo(0, 0);
		$overlay.fadeTo('fast', 0.8, function() {
			$popupthree.css('width', pwidth);
			$popupthree.css('height', pheight);
			$popupthree.find('.video-popup-middle').css('width', pwidth);
			$popupthree.find('.video-popup-middle').css('height', pheight);
			$popupthree.center(); 
			$popupthree.fadeIn('slow'); 
		});

		$(window).trigger('resize');
		$(window).trigger('scroll');
		return false;
	});
	
	$(window).bind('resize scroll', function() {
		if (!$.browser.msie || $.browser.version >= 7) return;

		$offset = Math.round($(window).height() / 2) + $(window).scrollTop();

		$popup = $('#careers-popup');
		$popuptwo = $('#whats-popup');
		$popupthree = $('#video-popup');
		$popup.css('top', $offset);
		$popuptwo.css('top', $offset);
		$offset = 200 + $(window).scrollTop();
		$popupthree.css('top', $offset);
		$('#careers-popup-overlay').css('top', $(window).scrollTop());
		$('#video-popup-overlay').css('top', $(window).scrollTop());
	});
	
	/*Custom Accordion*/
	$('#installation .description h1').click(function(){
		$(this).nextUntil('h1').slideToggle();
	});
	$('#installation .description h1:first').nextUntil('h1').show();
	
	$('#accessories .description h1').click(function(){
		$(this).nextUntil('h1').slideToggle();
	});
	$('#accessories .description h1:first').nextUntil('h1').show();
	
	$('.technical_page h1').click(function(){
		$(this).next('.technical-information').slideToggle();
	});
	
	$('.faq_entry h2').click(function(){
		if($(this).next('.answer').is(':hidden'))
		{
			$('.faq_entry .answer:visible').slideToggle('slow');
		}
		$(this).next('.answer').slideToggle('slow');
	});
	
	$('.faq_question').click(function(){
		if($(this).next('.faq_answer').is(':hidden'))
		{
			$('.faq_answer:visible').slideToggle('slow');
		}
		$(this).next('.faq_answer').slideToggle('slow');
	});
	
	
	/*Tabs*/
	if($('#tab-navigation').length > 0){
		var $tabs = $('#tab-navigation').tabs({ fxFade: true, fxSpeed: 'fast' });
	}
	if($('.accessories-navigation').length > 0){
		$('.accessories-navigation').tabs({ fxFade: true, fxSpeed: 'fast' });
	}
	if($('.spec-tabs').length > 0){
		$('.spec-tabs').tabs({ fxFade: true, fxSpeed: 'fast' });
	}


	$('.installation-process').click(function() { // bind click event to link
		$tabs.tabs( "select" , 1 );
		return false;
	});
	$('.activate-faq').click(function() { // bind click event to link
		$tabs.tabs( "select" , 3 );
		return false;
	});
	$('.sign-installation-process').click(function() { // bind click event to link
		$tabs.tabs( "select" , 3 );
		return false;
	});
	$('.sign-activate-faq').click(function() { // bind click event to link
		$tabs.tabs( "select" , 4 );
		return false;
	});
	$('.activate-funding').click(function() { // bind click event to link
		$tabs.tabs( "select" , 4 );
		return false;
	});
	$('.activate-spec').click(function() { // bind click event to link
		$tabs.tabs( "select" , 2 );
		return false;
	});
	
	/* LATEST NEWS */
	
	var news = $('.latest-news .news li');
	var len = $(news).size();
    var counter = 0;
	
	if(len > 1){
		$(news).hide();
		$(news[0]).show();
		setInterval(function() {
			$(news[counter]).hide( 'slide', {direction: 'up'} );
			 counter++;
			 if (counter == news.length) {
				 counter = 0;
			 }
			$(news[counter]).show( 'slide', {direction: 'down'} );
		}, 4000);
	}
	
	/* SEARCH BAR */
	
	$('#search-block-form .form-text').attr('title','SEARCH');
	//$('#search-block-form .form-text').val($('#search-block-form .form-text').attr('title'));
	
	$('#search-block-form').validate();
	
	
	$('.news-right-links .field-content a').attr('target','_blank');

	
});
