(function($) {
  var cache = [];
  $.preload_images = function(href_url, images) {
	for (i = 0;  i < images.length; i++) {
		var cached_image = document.createElement('img');
		cached_image.src = href_url+images[i].image;
		cache.push(cached_image);
	}
  }
})(jQuery)

// Uses animate() as an alternative for slideUp() - this is a quick fix for the annoying flicker in IE
jQuery.fn.slideUp_alt = function(speed, callback) {
    if (!$.browser.msie) {
        this.slideUp(speed, callback);
    } else {
        if (this.is(':visible')) { 
            var original_height = this.outerHeight();
            this.animate ({ height:'1px' }, speed,
                function() {
                    $(this).hide();
                    $(this).height(original_height);
                    if (callback) callback();
                } 
            );
        } else {
            if (callback) callback();
        }
    }
    return this;
}

 // Combines the original jQuery slideDown() with the workaround of slideUp_alt()
jQuery.fn.slideToggle_alt = function(speed, callback) {
    if (this.is(':hidden')) {
        return this.slideDown(speed, callback);
    } else {
        return this.slideUp_alt(speed, callback);
    } 
}

 // Scroll to an element, if it's not in view
jQuery.fn.scrollTo_inView = function(settings) {
    if (($(window).scrollTop() > this.offset().top) || (($(window).scrollTop()+$(window).height()) < this.offset().top)) { $.scrollTo(this, settings); }
    return this;
}

function input_bind_toggle(input_field, default_value) {
    input_field.bind('focus', {default_value:default_value},
        function(event) {
            if ($(this).val() == default_value) { $(this).val(''); $(this).removeClass('disabled'); }
        }
    );
    input_field.bind('blur', {default_value:default_value},
        function(event) {
            if ($(this).val() == default_value || !$.trim($(this).val())) { $(this).val(default_value); $(this).addClass('disabled'); }
        }
    );
}

/* ## */

function toggle_post(doc_id) {
	$.scrollTo('#post_'+doc_id,{duration:1000,onAfter:function() {location.hash = '#posts/'+doc_id}});
	$('#post_'+doc_id).toggleClass('selected');
	if ($('.post_'+doc_id+'.post_row').is(':visible')) {
		$('.post_'+doc_id+'.post_row .post').slideToggle(function() {
			$('.post_'+doc_id+'.post_row').toggle();
		});
	} else {
		$('.post_'+doc_id+'.post_row').toggle();
		$('.post_'+doc_id+'.post_row .post').slideToggle();
	}
}

function generate_posts(href_url, type, user_id, strings) {
	if (!$('#post_category_'+type).hasClass('selected')) {
		$('.post_categories a').removeClass('selected');
		$('#post_category_'+type).addClass('selected');
		$('.posts').remove();
		$.get(href_url,{'action':'get-posts','type':type, 'user-id':user_id},function(data) {
			//console.log(data);
			$('.sm_content').append('<div class="posts"></div>');
			if (data) {
				var html = '';
				html += '<table class="posts_container" cellspacing="1" cellpadding="0">';
				html += 	'<tr>';
				html += 		'<th><div class="first">'+strings.date+'</div></th>';
				html += 		'<th><div class="second">'+strings.client_name+'</div></th>';
				html += 		'<th><div class="third">'+strings.address+'</div></th>';
				html +=		'</tr>';
				$.each(data, function (i,item) {
					html += 	'<tr id="post_'+item.doc_id+'" class="post_'+item.doc_id+'" onclick="toggle_post(\''+item.doc_id+'\')" onmouseover="$(this).addClass(\'hover\')" onmouseout="$(this).removeClass(\'hover\')">';
					html += 		'<td><div class="label">'+item.date+'</div></td>';
					html += 		'<td><div class="label">'+item.parameters.system.client_name+'</div></td>';
					html += 		'<td><div class="label">'+item.parameters.system.address+'</div></td>';
					html +=		'</tr>';
					html +=		'<tr class="post_'+item.doc_id+' post_row">';
					html +=			'<td colspan="3">';
					html += 			'<div class="post">';
					html += 				'<div class="close" onclick="toggle_post('+item.doc_id+')">x <u>Close</u></div>';
					html +=					'<div class="container">';
					html += 					'<table cellspacing="0" cellpadding="0">';
					html += 						'<tr>';
					html += 							'<td>';
					html +=									'<div class="first_box">';
					html +=										'<div class="sub_title">'+strings.installed_system_details+'</div>';
					html +=										'<div><b>'+strings.country+': </b>'+item.parameters.system.country+'</div>';
					html +=										'<div><b>'+strings.address+': </b>'+item.parameters.system.address+'</div>';
					html +=										'<div><b>'+strings.client_name+': </b>'+item.parameters.system.client_name+'</div>';
					html +=										'<div><b>'+strings.category+': </b>'+item.parameters.system.category+'</div>';
					html +=										'<div><b>'+strings.product+': </b>'+item.parameters.system.product+'</div>';
					html +=										'<div><b>'+strings.serial_number+': </b>'+item.parameters.system.serial_number+'</div>';
					html +=									'</div>';
					html += 							'</td>';
					html += 							'<td>';
					html +=									'<div class="second_box">';
					html +=										'<div class="sub_title">'+strings.service_requests+'</div>';
					html +=										'<div class="link"><a href="'+href_url+'groups/support/services">'+strings.open_service_request+'</a> &rsaquo;</div>';
					html +=									'</div>';
					html += 							'</td>';
					html += 						'</tr>';
					html += 					'</table>';
					html +=					'</div>';
					html +=				'</div>';
					html +=			'</td>';
					html +=		'</tr>';
				});
				html += '</table>';
				$('.posts').append(html);
			} else {
				$('.posts').append(strings.no_results_found+'.');
			}
			setTimeout(function() {
				$('.posts').slideToggle();
			}, 800);
		},'json');
	}
}

/* ## */

function generate_faqs(href_url,selected_category_id,selected_sub_category_id, strings) {
	if ((selected_sub_category_id && !$('#faq_sub_category_'+selected_sub_category_id).hasClass('selected')) || (!selected_sub_category_id && selected_category_id && !$('#faq_category_'+selected_category_id).hasClass('selected'))) {
		
		if (selected_category_id) {
			$('.faq_categories a').removeClass('selected');
			$('#faq_category_'+selected_category_id).addClass('selected');
		}
		
		if (selected_sub_category_id) {
			$('.faq_sub_categories a').removeClass('selected');
			$('#faq_sub_category_'+selected_sub_category_id).addClass('selected');
		}
		
		if (!selected_sub_category_id) {
			$('.faq_sub_categories:visible').slideUp(400);
			setTimeout(function() {
				$('#faq_sub_categories_'+selected_category_id).slideDown(400);
			}, 400);
		}
		
		$('#faq_by_category .faqs').remove();
		var group_id;
		if (selected_sub_category_id) {
			group_id = selected_sub_category_id;
		} else {
			group_id = selected_category_id;
		}
		if (group_id) {
			$.get(href_url,{'action':'get-posts','type':'faq','group-id':group_id},function(data) {
				//console.log(data);
				$('#faq_by_category').append('<div class="faqs"></div>');
				
				if (data) {
					$.each(data, function (i,item) {
                        if (!lang_prefix || (item.parameters.language == undefined)) {
    					   item_question    = item.description_short ? item.description_short : item.title;
    					   var item_description = item.description;
    				    } else {
    				        var item_description_short = item.parameters.language[lang_prefix+'description_short'] != undefined ? item.parameters.language[lang_prefix+'description_short'] : item.description_short;
                            var item_title             = item.parameters.language[lang_prefix+'title'] != undefined ? item.parameters.language[lang_prefix+'title'] : item.title; 
    				        item_question = item_description_short ? item_description_short : item_title;
    				        var item_description = item.parameters.language[lang_prefix+'description'] != undefined ? item.parameters.language[lang_prefix+'description'] : item.description; 
    				    }
    				    item_question    = item_question.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;");
    				    //item_description = item_description.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;");
						$('#faq_by_category .faqs').append('<div id="faq_'+item.doc_id+'" class="faq"><div class="question" onclick="$.scrollTo(\'#faq_'+item.doc_id+'\',{duration:1000,onAfter:function() {location.hash = \'#faqs/'+item.doc_id+'\'}});$(\'#faq_'+item.doc_id+' .question\').toggleClass(\'bold\');$(\'#faq_'+item.doc_id+' .answer\').slideToggle()" onmouseover="$(this).addClass(\'hover\')" onmouseout="$(this).removeClass(\'hover\')">'+item_question+'</div><div class="answer"><div class="close" onclick="$(\'#faq_'+item.doc_id+' .question\').toggleClass(\'bold\');$(\'#faq_'+item.doc_id+' .answer\').slideToggle()">x <u>'+strings.close+'</u></div>'+item_description+'</div></div>');
					});
				} else {
					//$('.faqs').append(strings.coming_soon+'.');
				}
				
				setTimeout(function() {
					$('#faq_by_category .faqs').slideToggle();
				}, 800);
				
			},'json');
		}
	}
}

function generate_faqs_all(strings) {
    $('#faq_by_search .faqs').remove();
    $.get('/',{action:'get-faq-all'}, 
        function(data) {
            $('#faq_by_search').append('<div class="faqs"></div>');	
			if (data) {
                var faq_autocomplete_source = new Array();
				$.each(data, function (i,item) {
                    if (!lang_prefix || (item.parameters.language == undefined)) {
					   item_question    = item.description_short ? item.description_short : item.title;
					   var item_description = item.description;
				    } else {
				        var item_description_short = item.parameters.language[lang_prefix+'description_short'] != undefined ? item.parameters.language[lang_prefix+'description_short'] : item.description_short;
                        var item_title             = item.parameters.language[lang_prefix+'title'] != undefined ? item.parameters.language[lang_prefix+'title'] : item.title; 
				        item_question = item_description_short ? item_description_short : item_title;
				        var item_description = item.parameters.language[lang_prefix+'description'] != undefined ? item.parameters.language[lang_prefix+'description'] : item.description; 
				    }
				    //item_question    = item_question.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;");
				    item_question    = item_question.replace('<', "&lt;").replace('>', "&gt;");
				    faq_autocomplete_source[i] = item.doc_id+'::'+item_question;
				    //item_description = item_description.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;");
					$('#faq_by_search .faqs').append('<div id="faq_search_'+item.doc_id+'" class="faq"><div class="question" onclick="$.scrollTo(\'#faq_search_'+item.doc_id+'\',{duration:1000/*,onAfter:function() {location.hash = \'#faqs_search/'+item.doc_id+'\'}*/});$(\'#faq_search_'+item.doc_id+' .question\').toggleClass(\'bold\');$(\'#faq_search_'+item.doc_id+' .answer\').slideToggle_alt()" onmouseover="$(this).addClass(\'hover\')" onmouseout="$(this).removeClass(\'hover\')">'+item_question+'</div><div class="answer"><div class="close" onclick="$(\'#faq_search_'+item.doc_id+' .question\').toggleClass(\'bold\');$(\'#faq_search_'+item.doc_id+' .answer\').slideToggle()">x <u>'+strings.close+'</u></div>'+item_description+'</div></div>');
				});
				$('#faq_by_search .faq_query').autocomplete(faq_autocomplete_source,{matchContains:true,minChars:3,formatItem:function(row) {t=row[0].split('::');return t[1]},formatResult:function(row) {t=row[0].split('::');return t[1].replace('&lt;', "<").replace('&gt;', ">")}});
				$('#faq_by_search .faq_query').result(function(event,selected_item,formatted_item) {$('#faq_by_search .faq .answer').hide();$('#faq_by_search .faq .question').removeClass('bold');t=selected_item+'';selected_faq=t.split('::');$('#faq_by_search .faq').hide();$('#faq_search_'+selected_faq[0]).show().find('.question').click()}).focus();
			} else {
				//$('.faqs').append(strings.coming_soon+'.');
			}
			
			setTimeout(function() {
				$('#faq_by_search .faqs').slideToggle();
			}, 800);
        },'json'
    );
}

/* Support Module: Downloads */

function generate_downloads_categories(href_url, group_id, selected_group_id, level, query, strings) {
	// Reseting the query if it's false
	if (!query) {
		$('#query').val('');
	}
	// Removing any existing categories in select-boxes of the next levels and the current level
	if (level) {
		for (i = level; i <= 3; i++) {
			$('#downloads_categories_'+i+'_title').html('');
			$('#downloads_categories_'+i+' select').html('');
		}
	}
	// Showing the loader
	$('#downloads_categories_'+level+' select').css('background-image','url('+href_url+'images/global/loader_48x48.gif)');
	var downloads_container = $('#downloads_form');
	var overlay             = $('<div class="downloads_form_overlay"></div>').css('opacity','0.65').height(downloads_container.outerHeight()).width(downloads_container.outerWidth()).hide();
    downloads_container.children('.downloads_form_overlay').remove(); 
    overlay.prependTo(downloads_container).fadeIn();
	// Getting the categories
	if (level && level <= 3) {
		$.get(href_url,{'action':'get-downloads-categories','group-id':group_id},function(data) {
			if (data.categories) {
				var elements = '';
				$.each(data.categories, function (i,item) {
					elements += '<option value=\''+item.id+'\' '+(selected_group_id == item.id ? 'selected' : false)+'>'+(item[downloads_lang_prefix+'title'] ? item[downloads_lang_prefix+'title'] : item['title'])+'</option>';
				});
				// Appending the elements
				$('#downloads_categories_'+level+' select').append(elements);
				// Updating the column title
				if (data.parent_group.title) {
					$('#downloads_categories_'+level+'_title').html(data.parent_group[downloads_lang_prefix+'title'] ? data.parent_group[downloads_lang_prefix+'title'] : data.parent_group.title);
				}
				// Hiding the loader
				$('#downloads_categories_'+level+' select').css('background-image','');
				$('#downloads_form .downloads_form_overlay').delay(500).fadeOut();;
				if (selected_group_id) {
					generate_downloads_categories(href_url, selected_group_id, false, level+1, query, strings);
				} else {
					// Generating the files of this current selected group
					if (group_id != '169301') {
                        generate_downloads_files(href_url, group_id, level, query, true, strings,false);
                    }
				}
			} else {
				// Hiding the loader
				$('#downloads_categories_'+level+' select').css('background-image','');
				$('#downloads_form .downloads_form_overlay').delay(500).fadeOut();;
				if (selected_group_id) {
					generate_downloads_categories(href_url, selected_group_id, false, level+1, query, strings);
				} else {
					// Generating the files of this current selected group
					generate_downloads_files(href_url, group_id, level, query, false, strings,false);
				}
			}
		},'json');
	} else {
		// Hiding the loader
		$('#downloads_categories_'+level+' select').css('background-image','');
		$('#downloads_form .downloads_form_overlay').delay(500).fadeOut();;
		if (selected_group_id) {
			generate_downloads_categories(href_url, selected_group_id, false, level+1, query, strings);
		} else {
			// Generating the files of this current selected group
			generate_downloads_files(href_url, group_id, level, query, false, strings,false);
		}
	}
	
}

function generate_downloads_files(href_url, group_id, level, query, show_title, strings, use_animation) {
	// Removing any existing downloads_files content
	$('.downloads_files').html('');
	// Showing the loader
	$('.downloads_files').css('background-image','url('+href_url+'images/global/loader_48x48.gif)');
	if (use_animation) {
    	var downloads_container = $('#downloads_form');
    	var overlay             = $('<div class="downloads_form_overlay"></div>').css('opacity','0.65').height(downloads_container.outerHeight()).width(downloads_container.outerWidth()).hide();
        downloads_container.children('.downloads_form_overlay').remove(); 
        overlay.prependTo(downloads_container).fadeIn();
    }
	// Getting the download files details
	var get_vars = '';
	if (query) {
	   if (group_id) {
            get_vars = {'action':'get-downloads-files','query':query,'group-id':group_id};
        } else {
            get_vars = {'action':'get-downloads-files','query':query};
        }
	} else {
        get_vars = {'action':'get-downloads-files','group-id':group_id};
	}
	$.get(href_url,get_vars,function(data) {
		var file = '';
		if (data) {
			if (show_title) {
				file += '<div class="file">'+strings.please_select_product_or_language+'</div>';
			}
			$.each(data, function (i,item) {
				
				//file += 	'<div class="file" onclick="pageTracker._trackPageview(\''+item.link+'\');window.location=\''+item.link+'\'">';
				file += '<div class="file">';
				file +=		'<table cellspacing="0" cellpadding="0">';
				file +=			'<tr>';
				file +=				'<td class="image_container"><a href="'+item.link+'" target="_blank"><img src="'+(item.thumbnail_image_url ? item.thumbnail_image_url : 'files/images/item Logos/item_default_thumbnail.png')+'" alt=""></a></td>';
				file +=				'<td>';
				file += 				'<a href="'+item.link+'" target="_blank" class="f_title">'+item.title+'</a>';
				file += 				'<div class="f_content">';
				if (query) {
					file +=						strings.search_results+' &rsaquo; '+query;
				} else {
					if ($('#downloads_categories_1 option:selected').html()) {
						file +=					$('#downloads_categories_1 option:selected').html();
					}
					if ($('#downloads_categories_2 option:selected').html()) {
						file += 				' &rsaquo; '+$('#downloads_categories_2 option:selected').html();
					}
					if ($('#downloads_categories_3 option:selected').html()) {
						file += 				' &rsaquo; '+$('#downloads_categories_3 option:selected').html();
					}
				}
				file += 					'<br>';
				if (item.size) {
					file +=					item.size+' [kb]';
				}
				/*
				if ($('#downloads_categories_1_title').html()) {
					file +=						$('#downloads_categories_1_title').html()+': '+($('#downloads_categories_1 option:selected').html() ? $('#downloads_categories_1 option:selected').html() : strings.not_selected_yet)+'<br>';
				}
				if ($('#downloads_categories_2_title').html()) {
					file += 					$('#downloads_categories_2_title').html()+': '+($('#downloads_categories_2 option:selected').html() ? $('#downloads_categories_2 option:selected').html() : strings.not_selected_yet)+'<br>';
				}
				if ($('#downloads_categories_3_title').html()) {
					file += 					$('#downloads_categories_3_title').html()+': '+($('#downloads_categories_3 option:selected').html() ? $('#downloads_categories_3 option:selected').html() : strings.not_selected_yet)+'<br>';
				}
				*/
				file += 				'</div>';
				file +=				'</td>';
				file +=			'</tr>';
				file +=		'</table>';
				file += '</div>';
				
			});
		} else if (level == 1) {
			file += '<div class="file">'+strings.please_choose_a_category+'</div>';
		} else {
			file += '<div class="file">'+strings.no_results_found+'</div>';
		}
		// Hiding the loader
		$('.downloads_files').css('background-image','');
		$('#downloads_form .downloads_form_overlay').delay(500).fadeOut();;
		// Appending the items / no-results notification
		$('.downloads_files').append(file);
	},'json');
}

/* Distributors Module (map) - To order*/

function gd(href_url, article_id, description, strings) {
    $('.description').hide();
	// Removing any existing distributors
	$('.distributors').html('').addClass('loader');
	$.get(href_url,{'action':'get-distributors','article-id':article_id},function(data) {
		var elements = '';
		if (data && data[0].company) {
			$.each(data, function (i,distributor) {
				elements += '<div class="distributor">';
				if (distributor.type == 'use_main_page_description') {
					elements += description;
				} else if (distributor.type == 'no_results_updated_soon') {
					elements += strings.distributors_will_be_updated_soon;
				} else {
					elements += 	'<table cellspacing="0" cellpadding="0">';
					elements += 		'<tr>';
					elements += 			'<td><div class="logo"><img src="'+distributor.logo+'"></div></td>';
					elements += 			'<td><div class="separator"></div></td>';
					elements += 			'<td>';
					if (distributor.company) {
						elements += '<div class="company">'+distributor.company+'</div>';
					}
					if (distributor.type == 'no_results_office') {
						elements += '<div class="type">'+strings.no_results_general_office+'</div>';
					} else if (distributor.type != 'no_results_updated_soon') {
						elements += '<div class="type">'+strings[distributor.type]+'</div>';
					}
					if (distributor.phone) {
						elements += '<div class="phone"><span>'+strings.phone+':</span> <span dir="ltr">'+distributor.phone+'</span></div>';
					}
					if (distributor.email) {
						elements += '<div class="email">'+strings.email+': <a href="mailto:'+distributor.email+'" target="_blank">'+distributor.email+'</a></div>';
					}
					if (distributor.address) {
						elements += '<div class="address"><span>'+strings.address+':</span> <span dir="ltr">'+distributor.address+'</span>';
						if (distributor.country) {
							elements += ', <span class="country">'+distributor.country+'</span>';
						}
						elements += '</div>';
					}
					if (distributor.link) {
						elements += '<div class="link"><span>'+strings.website+'</span>: <span dir="ltr"><a href="http://'+distributor.link+'" target="_blank">'+distributor.link.replace(/http:\/\//,'')+'</a></span></div>';
					}

					if (distributor.contact_link) {
						elements += '<div class="link"><span>'+strings.contact_form+':</span> <span dir="ltr"><a href="http://'+distributor.contact_link+'" target="_blank">'+distributor.contact_link.replace(/http:\/\//,'')+'</a></span></div>';
					}
					elements += 			'</td>';
					elements += 		'</tr>';
					elements += 	'</table>';
				}
				elements +=	'</div>';
			});
			 // Hiding the loder
			$('.distributors').removeClass('loader');
			 // Appending the elements
            $('.distributors').append(elements);
		} else {
            $('.distributors').removeClass('loader');
			$('.description').show();
		}
	},'json');
}

/* ## */

function generate_home_showcase(href_url,chunks) {
	// Images are used as chunks of 3.
	var count = 1;
	$.each(chunks, function(i, chunk) {
		setTimeout(function() {
			$.each(chunk, function(j, object) {
				setTimeout(function() {
					$('#main_image_'+j).append('<div id="image_'+i+'_'+j+'" class="img"><img src="'+href_url+object.image+'"></div>');
					$('#image_'+i+'_'+j).slideDown(500, function() {
						if (object.link) {
							$('#main_image_'+j).bind('mouseup',function() {
								window.location = object.link;
							});
						} else {
							$('#main_image_'+j).unbind('mouseup');
						}
						setTimeout(function() {
							$('#image_'+i+'_'+j).remove();
						}, 5000);
					});
				}, j*250);
			});
			if (count == chunks.length) {
				generate_home_showcase(href_url,chunks);
			} else {
				count++;
			}
		}, (i+1)*4000);
	});
}

function generate_home_movie(movie_url,strings) {
	if ($('#home_movie').length > 0) {
		// Hiding the movie
		$('#home_movie').slideUp_alt(400,function() {
			$.scrollTo('.frame',{duration:1000,onAfter:function() {
				$('.home .links .video .text').html(strings.play_video);
				$('#home_movie').remove();
			}});
		});
	} else {
		// Showing the movie
		$('#middle #content .content_container').append('<div id="home_movie"></div>');
		$('#home_movie').slideDown(400,function() {
			$.scrollTo('#home_movie',{duration:1000,onAfter:function() {
				showcase('home_movie', 'swf', movie_url, 900, 350, '', '', '', '');
				$('.home .links .video .text').html(strings.hide_video);
			}});
		});
	}
}

/* ## */

function toggle_state_field(country, state_field, language) {
    var countries_with_states = new Array();
    countries_with_states['english'] = 'Australia,Canada,China,France,Germany,Italy,Russia,USA';
    countries_with_states['german']  = 'Australien,Kanada,China,Frankreich,Deutschland,Italien,Russische Föderation,USA';
    if (countries_with_states[language].indexOf(country) != -1) { 
        state_field.attr('disabled','').removeClass('disabled'); 
    } else {
        state_field.attr('disabled','disabled').addClass('disabled');
    }
}

/* ## */

$(document).ready(function() {
	$('form').attr('autocomplete','off');
	$('select').attr('autocomplete','off');
	$('input').attr('autocomplete','off');
});

