var site_id = 11;
var product_finder_category_id = 2;
var selected_banner = 0;
var anz_banner;
var banner_animation;

$(document).ready(
	function() {

/**
 * Show IE Version Warning
 */

		if (jQuery.browser.msie
		&&  jQuery.browser.version < '7.0'
		&&  $.cookie('ie_version_warning') != 'off'	)
		{
			$('#cb_ie').click(function(){
				$.cookie('ie_version_warning', 'off', {path: '/'});
				$.fn.colorbox.close()
			});

			$.fn.colorbox({href: '#PE_IEVersionWarning', inline: true, open:true, width: 640});
		}

/***
 * Banner on Homepage
 */

		try {
	    $('#PE_homeCycle').cycle({
        speed:			1000,
        timeout:		6000,
				pause: 			1
    	});

			$('div.PE_homeTeaser').hover(
				function() {
					splitValues = $(this).attr('id').split('_');
					teaser = splitValues[2];
					$('#PE_homeCycle').cycle('pause');
					$('div.PE_homeBanner').hide();
					$('div#PE_homeBanner_'+teaser).show().css('opacity', 1);
				},
				function() {
					splitValues = $(this).attr('id').split('_');
					teaser = splitValues[2];
					$('#PE_homeCycle').cycle('resume');

				}
			);
		}
		catch (e) {}

/***
 * Search Form
 */

		if ( $('form#PE_bannerSearchForm input.PE_text_search').length >= 1 )
		{
			var default_search_string = $('form#PE_bannerSearchForm input.PE_text_search').val();
			$('form#PE_bannerSearchForm input.PE_text_search').focus(
				function()
				{
					if ($(this).val() == default_search_string) $(this).val('');
				}
			).blur(
				function()
				{
					if ($(this).val() == '') $(this).val(default_search_string);
				}
			);
		}

/***
 * Banner Overlay
 */

		if ( $('#PE_olOverlay').html() != null
		&&   $('#PE_olOverlay').html() != '')
		{
			if ($.cookie('pe_banner_overlay') != 'off')
			{
				banner_href = $('#PE_olOverlay').html();

				$.fn.colorbox({
					href: banner_href,
					iframe: true,
					inline: false,
					open: true,
					innerWidth: 591,
					innerHeight: 532
				});

				$.cookie('pe_banner_overlay', 'off', {path: '/'})
			}
		}

/***
 * LIFE CARE Overlay
 */

		if ( $('#PE_lcOverlay').html() != null
		&&   $('#PE_lcOverlay').html() != '')
		{
			if ($.cookie('lc_banner_overlay') != 'off')
			{
				banner_href = $('#PE_lcOverlay').html();

				$.fn.colorbox({
					href: banner_href,
					iframe: true,
					inline: false,
					open: true,
					innerWidth: 800,
					innerHeight: 600
				});

				$.cookie('lc_banner_overlay', 'off', {path: '/'})
			}
		}

// BO Gallery-Cycle
		try {
			for ( i in banner ) {
				$('#PE_banner').append(
					'<img src="'+banner[i]+'" />'
				);
			}
		}
		catch(e) {}

		$('#PE_banner').cycle({
		    //fx:      'scrollRight',
		    fx:      'fade',
		    speed:    1000,
		    timeout:  5000,
				pause: 		1,
				next: 		'#PE_banner'
		});
// EO Gallery-Cycle

		$('#SLR_demoInteractiv').cycle({
		    //fx:      'scrollRight',
		    fx:      'fade',
		    speed:    1000,
		    timeout:  5000,
				pause: 		1,
				next: 		'#SLR_demoInteractiv'
		});

		/***
		 * Open Link-Target in Colorbox iFrame layer
		 * Anchors with this class must contain parameter width and height
		 */
		try {
			if ($('a.cbox_flexibleIframe').length > 0)
			{
				$('a.cbox_flexibleIframe').colorbox({
					innerWidth: function() {
						var href = $(this).attr('href').split('?');
						var query = href[1];
						var paramPairs = query.split('&');
						for (pair in paramPairs)
						{
							keyValue = paramPairs[pair].split('=');
							if (keyValue[0] == 'width')
							{
								return keyValue[1]
							}
						}
					},
					innerHeight: function() {
						var href = $(this).attr('href').split('?');
						var query = href[1];
						var paramPairs = query.split('&');
						for (pair in paramPairs)
						{
							keyValue = paramPairs[pair].split('=');
							if (keyValue[0] == 'height')
							{
								return keyValue[1]
							}
						}
					},
			  	iframe: true
			  });
			}
	  }
	  catch(e)
	  {
	  }

/**
 * Kamera-Finder
 */

		if ( $('#PE_productFinder').length > 0)
		{
			try
			{
				PHPSESSID = urlGetSessionID();
				$.getScript('/site/js/jquery.autocomplete.js',
					function() {
						getterUrl = 'getDCMSAjaxPlugin.php?site_id='+site_id+'&plugin_name=dcms_product_is_view_en&ajax_switch=product_selector&root_product_category_id='+product_finder_category_id+'&switch_lang=en';
						if ( PHPSESSID != '' )
						{
							getterUrl = getterUrl + '&PHPSESSID='+PHPSESSID;
						}
			  		$.getJSON(
			  			getterUrl,'',
			  			function(data)
			  			{
								product_url = data.product_url;
			  				category_array = data.category_array;
								$('input#PE_typeProductName').autocomplete(
									{ get : getMatches,
										callback: gotoProduct,
										multi: false,
										minchars: 0,
										timeout: 3000,
										delay: 100
									}
								);
			  			}
			  		);
					}
				);

				$('input#PE_typeProductName').focus(function() {
					txt_camera_name = $(this).val();
					$(this).val('');
				});
				$('input#PE_typeProductName').blur(function() {
					$(this).val(txt_camera_name);
				});

			} catch(e) {}
		}

/**
 * Retailer-List RS1000
 */

		if ($('#PE_typeRetailerName').length > 0)
		{
			try
			{
				PHPSESSID = urlGetSessionID();
				$.getScript('/site/js/jquery.autocomplete.js',
					function() {

						getterUrl = 'media/9680c78f03e35caf2c0cf4de5127d242/cashback2010_retailer.json';
						if ( PHPSESSID != '' )
						{
							getterUrl = getterUrl + '&PHPSESSID='+PHPSESSID;
						}

			  		$.getJSON(
			  			getterUrl,'',
			  			function(data)
			  			{
			  				retailer_array = data.retailer_array;
			  				// alert(retailer_array);

								$('input#PE_typeRetailerName').autocomplete(
									{ get : getRetailerMatches,
										callback: openRetailer,
										multi: false,
										minchars: 0,
										timeout: 10000,
										delay: 100
									}
								);
			  			}
			  		);
					}
				);

				$('input#PE_typeRetailerName').focus(function()
				{
					$(this).val('');
				});

/*
				$('input#PE_typeRetailerName').blur(function() {
					$(this).val(txt_camera_name);
				});
*/

			} catch(e) {}
		}

	}
);

/**
 * Extract the Session-Id from the URL-Get-Parameters
 */
function urlGetSessionID()
{
	sessionID = '';
	paramPair_array = window.location.search.substring(1).split('&');
	jQuery.each(paramPair_array, function(idx, val) {
		paramVal_array = val.split('=');
		if (paramVal_array[0] == 'PHPSESSID')
		{
			sessionID = paramVal_array[1];
			return false;
		}
	});
	return sessionID;
}

/**
 * Callbacks for JQuery AutoComplete ProductFinder
 */

function getMatches(typed)
{
	// alert('getMatches-A');
	var a = Array();
	jQuery.each(category_array, function(idx, cat) {
		product_array = cat.product_array;
		jQuery.each(product_array, function(idx, val) {
			product_name = val.product_name
			if (product_name.match(new RegExp(typed, "i")))
			{
				new_href = cat.category_url.replace(/__group_id__/g, cat.category_id);
				new_href = new_href.replace(/__product_id__/g, val.product_nr);

	   		a.push({id:val.product_id, value: val.product_name, info:"<span class=\"\">"+cat.category_name+"</span>", extra: new_href});
			}

		});
	});
  return a;
}

function gotoProduct(obj) {
	$('input#PE_typeProductName').blur();
	window.location.href = obj.extra;
}

function getAll()
{
	var a = Array();
	if (retailer_array)
	{
		// alert('getAll-A');

		jQuery.each(retailer_array, function(idx, retailer) {
   		a.push({id:idx, value:idx, info:"<div style=\"width: 200px; height: 40px;\"><a href=\"\">"+retailer.name+", "+retailer.postcode+"</a></div>", extra: new_href});
		});
	}
	else
	{
		// alert('getAll-B');
		jQuery.each(category_array, function(idx, cat) {
			product_array = cat.product_array;
			jQuery.each(product_array, function(idx, val) {
				product_name = val.product_name;
	   		a.push({id:val.product_id, value: val.product_name, info:"<a href=\""+new_href+"\">mehr &raquo;</a><br /><span class=\"\">"+cat.category_name+"</span><br /><span class=\"\">Artikelnr. "+val.product_nr+"</span>", extra: new_href});
			});
		});
	}

  return a;
}

/**
 * Callbacks for JQuery Retailer Cashback 2010
 */

function addVal2Str(val,str)
{
	if (str != '')
	{
		str += ', ';
	}

	str += val;

	return str;
}

function getRetailerMatches(typed)
{
	var a = Array();
	jQuery.each(retailer_array, function(idx, retailer)
	{
		name 			= retailer.name.replace(/&amp;/, "&");
		address1 	= retailer.address1;
		address2 	= retailer.address2;
		address3 	= retailer.address3;
		postcode 	= retailer.postcode;
		city 			= retailer.city;
		country   = retailer.country;
		link      = retailer.link;
		link_kr   = retailer.link_kr;
		link_k5   = retailer.link_k5;

		if (link == '')
		{
			link = 'http://www.pentax.co.uk/en/cashback-retailers.html'; // to show retailers without website
		}

		if (link.substr(0,7) != 'http://'
		&&  link.substr(0,7) != 'HTTP://')
		{
			link = 'http://'+link;
		}

		if (name.match(new RegExp(typed, "i")))
		{
			value = name;
			info  = '';

/*
			if (address1 != '')
			{
				info = addVal2Str(address1, info);
			}
			if (address2 != '')
			{
				info = addVal2Str(address2, info);
			}
			if (address3 != '')
			{
				info = addVal2Str(address3, info);
			}
			if (postcode != '')
			{
				value = addVal2Str(postcode, value);

			}
*/
			if (city != '')
			{
				value = addVal2Str(city, value);
//				info = addVal2Str(city, info);
			}
/*
			if (country != '')
			{
				value = addVal2Str(country, value);
				info = addVal2Str(country, info);
			}
			info = '<div>'+info+'</div>';
*/

   		a.push({
   			id: idx,
   			value: value,
   			info: info,
   			extra: link
   		});
		}
	});
  return a;
}

function openRetailer(obj)
{
	$('input#PE_typeRetailerName').blur();

	if (obj.extra != 'http://www.pentax.co.uk/en/cashback-retailers.html')
	{
		wopenfull(obj.extra,'full',-1,-1,-1,-1,true);
	}
	else
	{
		window.location.href = obj.extra;
	}
}

/**
 * Cycle Banner
 */

function PE_changeBanner()
{
	selected_banner++;
	if (selected_banner > anz_banner - 1 ) selected_banner = 0;
	// Preload des Banners
	var tmpImg = new Image();
	tmpImg.src = banner[selected_banner];
	// Ueberblenden
	$('#PE_bannerImg').fadeOut('slow',function() {
		$(this).attr('src',banner[selected_banner]);
		$(this).fadeIn('slow');
	});
}

/* Just for Debugging
*/
function outputObject(o) {
	var ret = '';
	for (var key in o)
	{
		ret = ret + key + ' = ' + o[key] + '\n';
	}
	return ret;
}

/**
* open window with some parameters
*/

	function wopen(link,wname,xsize,ysize,xpos,ypos,scrollbars,return_false)
	{
		if (scrollbars == '')
		{
			scrollbars = 'no';
		}

		if (xsize==-1)
			xsize=screen.availWidth-10;
		if (ysize==-1)
			ysize=screen.availHeight-60;
		if (xpos==-1)
			xpos=(screen.availWidth-xsize)/2;
		if (ypos==-1)
			ypos=(screen.availHeight-ysize)/2;

   	features = 'width='+xsize+',height='+ysize+',status=no,scrollbars='+scrollbars+',noresizable,top='+ypos+',left='+xpos+',screenY='+ypos+',screenX='+xpos;

		nwindow  = open(link, wname, features);
		nwindow.focus();

		if (return_false)
		{
			return false;
		}
	}

/**
* open new window with following parameters, all further settings active
*
* @param string link
* @param string wname
* @param int xsize
* @param int ysize
* @param int xpos
* @param int ypos
* @return bool (false)
*/

	function wopenfull(link,wname,xsize,ysize,xpos,ypos,return_false)
	{
		if (xsize==-1)
			xsize=screen.availWidth-10;
		if (ysize==-1)
			ysize=screen.availHeight-60;
		if (xpos==-1)
			xpos=(screen.availWidth-xsize)/2;
		if (ypos==-1)
			ypos=(screen.availHeight-ysize)/2;

   	features = 'width='+xsize+',height='+ysize+',status=no,location=yes,directories=no,menubar=yes,toolbar=yes,status=yes,scrollbars=yes,resizable=yes,dependent=no';

		nwindow  = open(link, wname, features);
		nwindow.focus();

		if (return_false)
		{
			return false;
		}
	}


