var site_id = 2;
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);
				}
			)
		}

/***
 * ColorBox init
 */		
		
		if ( $('a.cbox_image').length > 0 )
		{
			$('a.cbox_image').colorbox();
		}		
		
/***
 * 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: 800,
					innerHeight: 552
				});
/*
					innerWidth: 970,
					innerHeight: 750
 */
				
				$.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: '/'})
			}
		}

/***
 * PNG-Fix für IE 6
 */

		if ( $('#PE_page_1006, #PE_page_998').length >= 1 && $.browser.msie == true && $.browser.version == "6.0")
		{
			$.getScript('/site/js/jquery.pngfix.js',
				function() {
					$('#pngFix, #pngFix1').pngfix();
				}
			);
		}

		// 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'
		});


/***
 *  Content-Ad
 */

		if ($('#PE_contentAd').length > 0 && jQuery.trim($('#PE_contentAdHtml').html()) != '')
		{
			$.fn.colorbox({
				href: "#PE_contentAdHtml",
				inline: true,
				open: true,
				width: 600,
				title: false
			});
		}

		/***
		 * 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_de&ajax_switch=product_selector&root_product_category_id='+product_finder_category_id+'&switch_lang=de';
						if ( PHPSESSID != '' )
						{
							getterUrl = getterUrl + '&PHPSESSID='+PHPSESSID;
						}
			  		$.getJSON(
			  			getterUrl,'',
			  			function(data)
			  			{
			  				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) {}
		}
	}
);

/**
 * 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;
}

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

// *** Kamera-Finder:
function getMatches(typed)
{
	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;
}

// *** Kamera-Finder: Alle Kameras holen
function getAll()
{
	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;
   		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;
}


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;
		}
	}

/**
* schickt ein Formular an die Thickbox, wo es im IFRAME geöffnet wird (-> CommerceConnector)
*/
function tb_sendform(f,c)
{
  f.action.match(/(\bkeepThis=(true|false)&TB_iframe=true.+$)/);
  tb_show(c, 'about:blank?'+RegExp.$1);
  f.target=$('#TB_iframeContent').attr('name')
  return true;
}

/**
* schickt ein Formular an die Thickbox, wo es im IFRAME geöffnet wird (-> CommerceConnector)
*/
function cbox_sendform(f,c,w,h)
{
  f.action.match(/(\bkeepThis=(true|false)&TB_iframe=true.+$)/);
	$.fn.colorbox({
		title: c,
		href: "div#commerce_connector_result",
  	inline: true,
  	innerWidth: w,
  	innerHeight: h,
		onComplete: function() { $('div#commerce_connector_result').fadeIn('slow'); }
  });
  return false;
}

function initClickCount(selector)
{
	if ($(selector).size() > 0)
	{
		$(selector).each(function()
		{
			absUrl = false;
			container = $(this).parents('[@id]').attr('id');
			href = $(this).attr('href');

			if (ergebnis = href.match(/^http:\/\//i))
			{
				absUrl = true;
			}
			else if (ergebnis = href.match(/^https:\/\//i))
			{
				absUrl = true;
			}

			if (absUrl)
			{
				newHref = 'http://cnt.pentax.de/RD/?campaign=clicks&container=' + container + '&callback=' + urlencode(href);
				$(this).attr('href', newHref);
			}
		});
	}
}

function urlencode( str ) {

    var histogram = {}, tmp_arr = [];
    var ret = str.toString();

    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };

    // The histogram is identical to the one in urldecode.
    histogram["'"]   = '%27';
    histogram['(']   = '%28';
    histogram[')']   = '%29';
    histogram['*']   = '%2A';
    histogram['~']   = '%7E';
    histogram['!']   = '%21';
    histogram['%20'] = '+';

    // Begin with encodeURIComponent, which most resembles PHP's encoding functions
    ret = encodeURIComponent(ret);

    for (search in histogram) {
        replace = histogram[search];
        ret = replacer(search, replace, ret) // Custom replace. No regexing
    }

    // Uppercase for full PHP compatibility
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
        return "%"+m2.toUpperCase();
    });

    return ret;
}
