jQuery.noConflict();

function c(cmd) { console.log(cmd); }

var App = {
	iframe: function(elm) {
		var $iframe = jQuery(elm);
		$iframe.height($iframe.contents().height());
		jQuery('a', $iframe.contents()).attr('target', '_parent');
	},
	
	submit: function(elm) {
		var $elm = jQuery('#' + elm);
		jQuery.post("/services/subscribe_validation.php", $elm.serialize(), function(data) {
			if (data === '1') {
				$elm.submit();
			} else {
				$('.error', $elm).html(data);
				$('.info', $elm).hide();
			} // if
		});
		return false;	
	},

	maps: {
		marker: null,
		list: [],
		callback: null,
	
		init: function(callback) {
			var gScript = document.createElement("script"),
					mScript = document.createElement("script"),
					sScript = document.createElement("script"),
					type = "text/javascript";

			// Setup DOM
			gScript.type = type;
			gScript.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=App.maps.load";
      
			mScript.type = type;
			mScript.src = "/javascript/frontend/markerclusterer_compiled.js";

			sScript.type = type;
			sScript.src = "/javascript/frontend/searcher.min.js";

			// Append scripts
			document.body.appendChild(gScript);
			document.body.appendChild(mScript);
			document.body.appendChild(sScript);
			
			App.maps.callback = callback;
		},

		load: function() {
			App.maps.marker = {
				icon: new google.maps.MarkerImage('/images/maps/marker_sprite.png', new google.maps.Size(24, 33), new google.maps.Point(0, 0), new google.maps.Point(8, 29)),
				shadow: new google.maps.MarkerImage('/images/maps/marker_sprite.png', new google.maps.Size(28, 33), new google.maps.Point(24, 0), new google.maps.Point(4, 29))
			};
		  
			var $ = jQuery,
					styles = [
						{
							url: '/images/maps/cluster_small.png',
							width: 50,
							height: 50,
							textColor: '#FFFFFF'
						},
						{
							url: '/images/maps/cluster_medium.png',
							width: 60,
							height: 60,
							textColor: '#FFFFFF'
						},
						{
							url: '/images/maps/cluster_large.png',
							width: 70,
							height: 70,
							textColor: '#FFFFFF'
						}
					],
					options = {
						zoomOnClick: true,
						averageCenter: true,
						gridSize: 40,
						styles: styles
					},
					maps = App.maps.list;
					
			if (maps.length > 0) {
				$.each(maps, function(i, item) {
					var mapOptions = {
								zoom: item.zoom,
								center: new google.maps.LatLng(item.lat, item.lng),
								mapTypeId: google.maps.MapTypeId.ROADMAP,
								streetViewControl: false,
								mapTypeControl: item.size > 1
							},
							mapElem = $('#' + item.id).width(item.width).height(item.height)[0];
					item.map = new google.maps.Map(mapElem, mapOptions);
					if (item.size == 1) {
						App.maps.addMarker(item, item);
					} else {
						$.get("/services/stores.php", function(data) {
							if (data && data.stores && data.stores.length > 0) {
								var content = {};
								$.each(data.stores, function(j, store) {
									App.maps.addMarker(item, {lat: store.geocode.lat, lng: store.geocode.lng, html: store.html});
									if (!content[store.country]) {
										content[store.country] = [];
									}
									content[store.country].push({ address: store.address, city: store.city, geocode: store.geocode });
								});

								if (data.countries) {
									$.each(data.countries, function(j, country) {
										App.maps.addCMarker(item, {lat: country.geocode.lat, lng: country.geocode.lng, html: country.html});
										if (content[country.name]) {
											content[country.name]['title'] = country.title;
										}
									});
								}

								if (item.size == 2) {
									item.cluster = new MarkerClusterer(item.map, item.markers, options);
									item.info = null;
									if (item.cMarkers) {
										$.each(item.cMarkers, function(j, marker) {
											marker.setMap(null);
										});
									}
								} else {
									item.cluster = new MarkerClusterer(item.map, [], options);
									item.info = $('#gm_info');
								}
								google.maps.event.addListener(item.map, 'zoom_changed', function() {
									if (item.map.getZoom() < 5) {
										if (item.cluster.getTotalMarkers() > 0) {
											item.cluster.clearMarkers();
										}
										if (item.map.getZoom() == 4) {
											if (item.info && !item.info.data('gm_closed')) {
												item.info.fadeIn();
											}

											if (item.cMarkers) {
												$.each(item.cMarkers, function(j, marker) {
													marker.setMap(item.map);
												});
											}
										}
									} else {
										if (item.cluster.getTotalMarkers() == 0) {
											item.cluster.addMarkers(item.markers);
										}
										if (item.map.getZoom() == 5) {
											if (item.info && !item.info.data('gm_closed')) {
												item.info.fadeOut();
											}

											if (item.cMarkers) {
												$.each(item.cMarkers, function(j, marker) {
													marker.setMap(null);
												});
											}
										}
									}
								});
								item.content = content;
								item.search_control = App.maps.searchControl(item);
								item.search_control.index = 1;
								item.map.controls[google.maps.ControlPosition.TOP_RIGHT].push(item.search_control);
							}
						}, "json");
					}
				});

				if (typeof App.maps.callback == 'function') {
					App.maps.callback();
				}
			}
		},

		addMap: function(data) {
			App.maps.list.push(data);
		},

		addMarker: function(ref, data) {
			ref.markers = ref.markers || [];
			var marker = new google.maps.Marker({
				position: new google.maps.LatLng(data.lat, data.lng),
				icon: App.maps.marker.icon,
				shadow: App.maps.marker.shadow
			}), infowindow;
			if (ref.size == 1) { marker.setMap(ref.map); }
			if (data.html) {
				infowindow = new google.maps.InfoWindow({
					content: data.html
				});
				google.maps.event.addListener(marker, 'click', function() {
					infowindow.open(ref.map, marker);
				});
			}
			ref.markers.push(marker);
		},
		
		addCMarker: function(ref, data) {
			ref.cMarkers = ref.cMarkers || [];
			var marker = new google.maps.Marker({
				position: new google.maps.LatLng(data.lat, data.lng),
				icon: App.maps.marker.icon,
				shadow: App.maps.marker.shadow,
				map: ref.map
			}), infowindow;
			if (data.html) {
				infowindow = new google.maps.InfoWindow({
					content: data.html
				});
				google.maps.event.addListener(marker, 'click', function() {
					infowindow.open(ref.map, marker);
				});
			}
			ref.cMarkers.push(marker);
		},

		searchControl: function(data) {
			var $ = jQuery,
					$control = $('<div/>', { 'class': 'search-control' }),
					$container = $('<div/>', { 'class': 'search-container' })
						.appendTo($control),
					$icon = $('<div/>', { 'class': 'search-icon', 'title': data.search_text })
						.appendTo($container),
					$input = $('<input type="text" class="search-input empty" />')
						.val(data.search_help_text)
						.data('help-text', data.search_help_text)
						.appendTo($container),
					$content = $('<div/>', { 'class': 'search-content' })
						.appendTo($control).hide();
			
			var searcher = new Searcher(data.content, function(query, item) {
					var rx = new RegExp('(' + query + ')', 'i');
					return item.address.match(rx) || item.city.match(rx);
				}, function(query, list) {
					var $html = $(), rx = new RegExp('(' + query + ')', 'ig');
					$.each(list, function(alt, country) {
						var $title = $('<div/>', { 'class': 'content-title', 'html': country.title }),
								$ul = $('<ul/>', { 'class': 'content-list' });

						$.each(country, function(i, store) {
							$ul.append($('<li/>', { 'class': 'content-item', 'html': store.address.replace(rx, "<strong>$1</strong>") + '<br />' + store.city.replace(rx, "<strong>$1</strong>") }).data('geocode', store.geocode));
						});
						$html = $html.add($title);
						$html = $html.add($ul);
					});
					$html.first().addClass('first');
					return $html;
				}
			);

			$icon.click(function() { $input.focus(); });

			$input.focus(function() {
				if ($.trim($input.val()) == $input.data('help-text')) {
					$input.val('').removeClass('empty');
				}
				if ($input.data('value') && !$content.is(':empty')) {
					$content.show();
				}
			}).blur(function() {
				if ($.trim($input.val()) == '') {
					$input.val($input.data('help-text')).addClass('empty');
				}
				if (!$content.data('hover')) {
					$content.hide();
				}
			}).keyup(function(event) {
				if (!$input.hasClass('empty')) {
					var val = $.trim($input.val()), content;
					if (val.length > 1) {
						if (val != $input.data('value')) {
							content = searcher.search(val);
							$input.data('value', val);
							$content.empty().append(content.list);
							if (content.count > 10) {
								$content.addClass('limit');
							} else {
								$content.removeClass('limit');
							}
						}
						if (content && content.count > 0) {
							$content.show();
						} else {
							$content.hide();
						}
					} else {
						$content.hide();
						$input.removeData('value');
					}

					if ($content.is(':visible')) {
						var items = $('.content-item', $content), count = items.length, index = -1;
						if (count > 0) {
							items.each(function(i) {
								if (items.eq(i).hasClass('active')) {
									index = i;
								}
							});
							switch (event.keyCode) {
								case 40: // Down
									if (index >= 0 && index < count - 1) {
										items.eq(index++).removeClass('active');
										items.eq(index).addClass('active');
									} else {
										items.last().removeClass('active');
										items.first().addClass('active');
										index = 0;
									}
									break;
								case 38: // Up
									if (index > 0) {
										items.eq(index--).removeClass('active');
										items.eq(index).addClass('active');
									} else {
										items.first().removeClass('active');
										items.last().addClass('active');
										index = count - 1;
									}
									break;
								case 13: // Enter
									if (index !== -1) {
										items.eq(index).click();
									}
									break;
							}
							if (index !== -1) {
								var item = items.eq(index), top = item.position().top, height = item.height();
								if (top - height < 0 || $content.height() < top + height) {
									$content.scrollTop($content.scrollTop() + top - height);
								}
							}
						}
					}
				}
			});

			$content.delegate('.content-item', 'mousemove', function() {
				$('.content-item', $content).removeClass('active');
				$(this).addClass('active');
			}).delegate('.content-item', 'mouseleave', function() {
				$(this).removeClass('active');
			}).delegate('.content-item', 'click', function() {
				var geocode = $(this).data('geocode');
				data.map.panTo(new google.maps.LatLng(geocode.lat, geocode.lng));
				data.map.setZoom(parseInt(geocode.zoom));
				$input.blur();
				$content.hide();
			}).hover(
				function() { $content.data('hover', true); },
				function() { $content.data('hover', false); }
			).data('hover', false);

			$('#' + data.id).mousedown(function() { $input.blur(); });

			return $control[0];
		}
	}
};

jQuery(function($) {

	$attachments = $('div#files_container').hide();	
	$('a#attachments_button').click(function() {
		$(this).hide();
		$attachments.fadeIn();
	}).show();

	var Help = {
		value: '',
		$help: $('div#helpSearch'),
		$input: $('form#formSearch input'),
		view: function() {
			if (this.$help.data('hover') || this.$input.data('focus') && this.value.length > 1) {
				this.$help.show();
			} else {
				this.$help.hide();
			}
		},
		init: function() {
			this.$input.keyup(function(event) {
				var val = $(this).val();
				if (val.length > 1) {
					if (val != Help.value) {
						$.post("/services/helpsearch.php", { query: val }, function(data) {
							if (data.length > 0) {
								var html = '';

								var rx = new RegExp('(' + val + ')', "i");
								for (var key in data) {
									html += '<a href="' + data[key].url + '">' + data[key].name.replace(rx, "<strong>$1</strong>");
									if (data[key].category) {
										html += '<span class="category"> ' + data[key].category + '</span>';
									}
									html += '</a>';
								}

								$('.cc', Help.$help).html(html);
								Help.$help.show();
								if (Help.$help.width() > 190) { 
									Help.$help.css({'right' : '-1px', 'left' : 'auto'});
								} else {
									if ($.browser.webkit) { Help.$help.css({'left' : '7px', 'right' : 'auto'}); } 
									else if ($.browser.mozilla) { Help.$help.css({'left' : '0', 'right' : 'auto'}); }
									else if ($.browser.msie) { 
										if ($.browser.version == 9) { Help.$help.css({'left' : '7px', 'right' : 'auto'}); }
										else { Help.$help.css({'left' : '-3px', 'right' : 'auto'}); }
									}
									else { Help.$help.css({'left' : '-2px', 'right' : 'auto'}); }
								}
								
							} else {
								Help.$help.hide();
							}
						}, "json");
					}
				} else {
					Help.$help.hide();
				}
				Help.value = val;
				
				//Navigate results with arrow up/down
				$('#formSearch').submit(function(){
					if(Help.$help.find('a').hasClass('active')) {
						return false;
					} 
				});
				
				if(Help.$help.is(':visible')) {
					switch(event.keyCode) {
						case 40:
							if(Help.$help.find('a').not(':last').hasClass('active')) {
								Help.$help.find('a.active').removeClass('active').next('a').addClass('active');
							} else {
								Help.$help.find('a:first').addClass('active').siblings('a').removeClass('active');
							}						
						break;
						case 38:
							if(Help.$help.find('a').not(':first').hasClass('active')) {
								Help.$help.find('a.active').removeClass('active').prev('a').addClass('active');
							} else {
								Help.$help.find('a:last').addClass('active').siblings('a').removeClass('active');
							}												
						break;
						case 13:
							if(Help.$help.find('a').hasClass('active')) {
								window.open(Help.$help.find('a.active').attr('href'), '_self');
								event.preventDefault();
								return false;						
							}
						break;
					}
				}
			
			}).focus(function() {
				Help.$input.data('focus', true); Help.view();
			}).blur(function() {
				Help.$input.data('focus', false); Help.view();
			});

			this.$help.hover(
				function() { Help.$help.data('hover', true); },
				function() { Help.$help.data('hover', false); Help.view(); }
			).data('hover', false);
		}
	};
	Help.init();

	var language = {
		init: function() {
			$('#countrySelection .flagBtn').mouseenter(function() {
				$(this).siblings('.dropdown').css('display', 'block');
			});
			
			$('#countrySelection .dropdown').mouseleave(function() {
				$(this).css('display', 'none');
			});
		}
	}
	language.init();
	
	
/******************************************************
 * PRODUCT SLIDER
 ******************************************************/
		var ProductGallery = {
			currentPage: 0,
			numOfPages: 0,
			slideDis: 0,
			numOfElem: 0,
			extraLIs: 0,
			elemPerPage: 0,
			slideDistance: 0,
			selected: 0,
			navBot: 0,
			frame: 0,
			currentTab: 0,
		
			init: function(sel, slideDis, noElem, styling) {
				selected = $(sel);
				currentTab = 0;
				numOfElem = selected.find('ul.ss:eq('+currentTab+') li').length; 
				navBot = selected.find('.nav-bottom');
				slideDistance = slideDis;
				currentPage = 0;
				$this = this;
				numOfPages = 1;
				elemPerPage = noElem;
				frame = 0;
				extraLIs = 0;

				selected.find('ul.ss:first').css('display', 'block');
				
				if (numOfElem > noElem) {
					$('.box-slideshow-nav-left').css('display', 'block');
					$('.box-slideshow-nav-right').css('display', 'block');
					
					numOfPages = Math.ceil(numOfElem/elemPerPage);
					//If any tabs
					if(selected.find('.tabs').length) { 
						selected.find('ul.ss').each(function(){ $(this).find('li:first').addClass('first'); });
						$this.tabInteraction(); 
					}
					//If more elements per page than 1
					if(elemPerPage > 1) { $this.addEmptyLI(); }
					//If any custom styling needed
					if(styling) {$this.customStyling();}
					//If any bottom navigation
					if(selected.find('.nav-bottom').length) {
						$this.createBottomNavigation();
						$this.switchBottomActive();
						$this.navBottomInteraction();
					}
					$this.leftNavigation(); 
					$this.rightNavigation();
					
				}			
			},
			
			//Resets carousel
			resetCaraousel: function() {
				selected
				.find('ul.ss:eq('+currentTab+') li')
				.each(function() {
					if($(this).hasClass('first')) { return false; }
					else {
						selected.find('ul.ss:eq('+currentTab+') li:last').after($(this));
					}
				});
				
				selected
				.find('ul.ss:eq('+currentTab+')')
				.css({'margin-left' : 0, 'display' : 'block'})
				.siblings('ul').css('display', 'none');
				
				numOfElem = selected.find('ul:eq('+currentTab+') li').length; 
				navBot.html('');
				
				if (numOfElem > $this.elemPerPage) {
					$('.box-slideshow-nav-left').css('display', 'block');
					$('.box-slideshow-nav-right').css('display', 'block');
					numOfPages = Math.ceil(numOfElem/elemPerPage);
					currentPage = 0;
					frame = 0;
					$this.addEmptyLI();
					$this.customStyling();
					$this.createBottomNavigation();
					$this.switchBottomActive();
				} else {
					$('.box-slideshow-nav-left').css('display', 'none');
					$('.box-slideshow-nav-right').css('display', 'none');
				}
			},
			
			//Adds empty li
			addEmptyLI: function() {
				extraLIs = (numOfPages * elemPerPage) - numOfElem;
				for(i=0; i<extraLIs; i++) { selected.find('ul.ss:eq('+currentTab+')').append('<li></li>'); }
			},
			
			//Custom styles/function
			customStyling: function() {
				selected.find('ul.ss:eq('+currentTab+') li:nth-child(4n)').css('border-right', '0');
			},
			
			//Creation of bottom navigation 
			createBottomNavigation: function() {
				for(i=0; i < numOfPages; i++) {
						navBot.append('<span></span>');
				}
			},
			
			// Bottom navigation interaction
			navBottomInteraction: function() {
			
				navBot.find('span').live('click', function() {
					var navIndex = navBot.find('span').index(this);
					if(navIndex != currentPage) {
						navBot.find('span:eq('+(navIndex)+')').addClass('active').siblings('span').removeClass('active');
						
						if(!selected.find('ul.ss:eq('+currentTab+') li:first').hasClass('first')) {
							selected
							.find('ul.ss:eq('+currentTab+') li')
							.each(function() {
								if($(this).hasClass('first')) { return false; }
								else {
									selected.find('ul.ss:eq('+currentTab+') li:last').after($(this));
								}
							});
							
							selected.find('ul.ss:eq('+currentTab+')').css('margin-left', -slideDistance*currentPage);
							selected.find('ul.ss:eq('+currentTab+')').animate({  marginLeft: -(navIndex*slideDistance) }, 750);
							currentPage = navIndex;
							frame = navIndex;
						} else {
							selected.find('ul.ss:eq('+currentTab+')').animate({  marginLeft: -(navIndex*slideDistance) }, 750);
							currentPage = navIndex;
							frame = navIndex;
						}
					}
				});
			},
			
			//Changing active on bottom navigation
			switchBottomActive: function() {
				navBot.find('span:eq('+(currentPage)+')').addClass('active').siblings('span').removeClass('active');
			},

			//Left navigation
			leftNavigation: function() {
				$('.box-slideshow-nav-left').bind('click', function() {
					$(this).unbind('click');
					$('.box-slideshow-nav-right').unbind('click');					
					
					if(frame == 0) {
						for(i=0;i<elemPerPage; i++) { 
							selected.find('ul.ss:eq('+currentTab+')').prepend(selected.find('ul.ss:eq('+currentTab+') li').eq((numOfElem+extraLIs)-1));
						}
						selected.find('ul.ss:eq('+currentTab+')').css('margin-left', -slideDistance);
						selected.find('ul.ss:eq('+currentTab+')').animate({  marginLeft: -(frame*slideDistance) }, 750, function() { $this.leftNavigation(); $this.rightNavigation(); });
						frame = 0;
					} else {
						selected.find('ul.ss:eq('+currentTab+')').animate({  marginLeft: -(frame-1)*slideDistance }, 750, function() { $this.leftNavigation(); $this.rightNavigation(); });
						frame--;
					}
					
					currentPage == 0  ? currentPage = (numOfPages-1) : currentPage--;
					$this.switchBottomActive();
				});
			},
			
			//Right navigation
			rightNavigation: function() {
				$('.box-slideshow-nav-right').bind('click', function() {
					$(this).unbind('click');
					$('.box-slideshow-nav-left').unbind('click');		
					
					if(frame == numOfPages-1) {
						for(i=0; i<elemPerPage; i++) { 
							selected.find('ul.ss:eq('+currentTab+')').append(selected.find('ul.ss:eq('+currentTab+') li').eq(0));
						}
						selected.find('ul.ss:eq('+currentTab+')').css('margin-left', -slideDistance*(frame-1));
						selected.find('ul.ss:eq('+currentTab+')').animate({  marginLeft: -(frame*slideDistance) }, 750, function() { $this.leftNavigation(); $this.rightNavigation(); });
						frame = numOfPages-1;
					} else {
						selected.find('ul.ss:eq('+currentTab+')').animate({  marginLeft: -((frame+1)*slideDistance) }, 750, function() { $this.leftNavigation(); $this.rightNavigation(); });
						frame++;
					}
										
					currentPage == (numOfPages-1)  ? currentPage = 0 : currentPage++;
					$this.switchBottomActive();
				});			
			},
			
			// Show or hide navigation
			navigationVisibility: function() {
				if (currentPage == 1) {
					$('.box-slideshow-nav-left').css('display', 'none');
					$('.box-slideshow-nav-right').css('display', 'block');
				} else if (currentPage == numOfPages) {
						$('.box-slideshow-nav-right').css('display', 'none');
						$('.box-slideshow-nav-left').css('display', 'block');
				} else {
						$('.box-slideshow-nav-left').css('display', 'block');
						$('.box-slideshow-nav-right').css('display', 'block');
				}
			},
			
			//Tab interactivity
			tabInteraction: function() {
				selected.find('.tabs .tab-outer:first').addClass('active');
				selected.find('.tabs .tab-outer').click(function(){
					var tempIndex = selected.find('.tabs .tab-outer').index(this);
					if(currentTab != tempIndex) {
						currentTab = tempIndex;
						$(this).addClass('active').siblings('.tab-outer').removeClass('active');
						//selected.find('ul:eq('+currentTab+') li:first').addClass('first');
						$this.resetCaraousel();
					}
				});
			}
		
		};
		//ProductGallery.init(parent element, slide distance, number of elements visible at a time, custom styling)
		if ($('.m56').length) { ProductGallery.init($('.m56'), 979, 4, true); }
		if ($('.m41').length) { ProductGallery.init($('.m41'), 383, 1, false); }

/******************************************************
 * GENERAL FUNCTIONS
 ******************************************************/
		var GeneralFunctions = {
			multiSelect: function() {
				var $container = $('.m10 .select');
				var listTitle = $('#text_cities_available', $container).remove().html();
				var selectedTitle = $('#text_cities_selected', $container).remove().html();
				$('.listSelectArea').selectMultipleList({
					sortValue : false,
					sortAsc : true,
					sortNum : false,
					titleList : listTitle,
					titleSelected : selectedTitle
				});
			},
			titleHelp: function() {
				$('.m10 .select .title-help').each(function() {
					var $this = $(this), offset = 25, $position = $this.position(), $offset = $this.offset(), position = {
						left: $position.left - $offset.left + offset,
						top: $position.top - $offset.top
					},
					$tooltip = $('<span/>', {
						'class': 'title-help-tooltip',
						'html': $this.attr('title')
					});
					$this.removeAttr('title').append($tooltip);

					$this.mouseover(function() {
						$tooltip.css('opacity', 0.9).fadeIn(200);
					}).mousemove(function(mouse) {
						$tooltip.css({left: position.left + mouse.pageX, top: position.top + mouse.pageY});
					}).mouseout(function() {
						$tooltip.fadeOut(200);
					});
				});
			},
			init: function() {
				this.multiSelect();
				this.titleHelp();
			}
		}
		
		if ($(".listSelectArea").length) { GeneralFunctions.init(); }
		
});

