var COMPARE_COUNT = 0;
var IMG_LOADING = '<img src="/i/ajax-loader.gif" class="loading" />';
var GREY_LOADING = '<img src="/i/grey-loading.gif" class="loading" />';

jQuery.easing['BounceEaseOut'] = function(p, t, b, c, d) {
	if ((t/=d) < (1/2.75)) {
		return c*(7.5625*t*t) + b;
	} else if (t < (2/2.75)) {
		return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
	} else if (t < (2.5/2.75)) {
		return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
	} else {
		return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
	}
};

$(document).ready(function()
{
	var obj_div_menu = $('div.menu'); var SUBMENU = false;
	// menu shadow
	obj_div_menu.find('>ul>li:gt(0)').hover(
	    function() { obj_div_menu.find('span.hover').css( { left: $(this).position().left - 3 }).show(); },
	    function() { obj_div_menu.find('span.hover').hide(); }
	);
	obj_div_menu.find('>ul>li:eq(0)').hover(
	    function() { obj_div_menu.find('span.hover-first').show(); },
	    function() { obj_div_menu.find('span.hover-first').hide(); }
	)
	// sub menu
	.find('a').hover(
	    function() { SUBMENU = false; obj_div_menu.find('div.sub').show(); },
	    function() { setTimeout(function() { if (!SUBMENU) obj_div_menu.find('div.sub').hide(); }, 50)}
	);
	obj_div_menu.find('div.sub').hover(
	    function() { SUBMENU = true; $(this).show(); },
	    function() { $(this).hide(); }
	);
	// search input
	obj_div_menu.find('input.text').bind({
		focus: function(){
			if ($(this).val() == valueSearch) $(this).val('');
		},
		blur: function(){
			if ($(this).val() == '') $(this).val(valueSearch);
		}
	});

	$('div.header div.support a.new-window').click(function(){
		window.open(this.href, 'feedback', 'height=320,width=250');
		return false;
	});

	var bodyClass = $('body').attr('class');

	if (bodyClass == 'products') {
		// compare logic
		var obj_products_li = $('#products li');
		obj_products_li.find('input').click(function(e){
			var checked = obj_products_li.find('input:checked').length; var $this = $(this);
			if (checked < 5)
			{
				$this.parent().toggleClass('active');
				obj_products_li.find('button').hide();
				if (checked > 1)
				{
					if ($this.parent().attr('class') == 'active')
					{
						$this.parent().find('button').show();
					}
					else
					{
						$('#products li.active:last button').show();
					}
				}
			}
			else
			{
				e.preventDefault();
			}
		});

		obj_products_li.find('button').click(function(){
			var url = '/products/compare/'; var i = 0;
			obj_products_li.find('input:checked').each(function(){
				if (i++ > 0) url += ':';
				url += $(this).attr('id');
			});
			location.href = url+'/';
			return false;
		});

		var checked = obj_products_li.find('input:checked').length;
		if (checked > 0)
		{
			obj_products_li.find('input:checked').each(function(){ $(this).parent().addClass('active'); } );
			if (checked > 1) $('#products li input:checked:last').parent().find('button').show();
		}
		Cufon.replace('div.left ul.compare li h5', { fontFamily: 'Myriad Pro' });
	}
	else if (bodyClass == 'item') {
		productPage();
	}
	else if (bodyClass == 'compare') {
		var obj_compare_table = $('#compare-table');
		obj_compare_table.find('span.comp').after(IMG_LOADING);
		// add comparing items
		$('ul#carousel li').click(function(){
			if (COMPARE_COUNT < 4)
			{
				var reader_id = $(this).attr('id').substring(1);
				if ($('#c'+reader_id).length == 0)
				{
					compareTableAdd(reader_id);
				}
			}
		});
		// remove comparing items
		obj_compare_table.find('th a.border span').live('click', function(){
			var num = $(this).attr('num');
			obj_compare_table.find('tr').find('th:eq(' + num + ')').remove();
			obj_compare_table.find('tr').find('td:eq(' + num + ')').remove();
			compareTableUpdate();
			return false;
		});
		compareTableUpdate();
		Cufon.replace('#compare-table th a.border i', { fontFamily: 'Myriad Pro' });
	}//else if (bodyClass == 'compare') {
	if (bodyClass == 'news' || bodyClass == 'new') {

		// begin SUBSCRIBE FORM
		var obj_subscribe = $('#subscribe');
		obj_subscribe.find('input.text')
		.focus(function(){ if ($(this).val() == formEmail) $(this).val('').css('color', '#221E1F'); })
		.blur(function(){ if ($(this).val() == '') $(this).val(formEmail) });
		obj_subscribe.find('input.submit').after(IMG_LOADING);
		//action switcher
		$('#add').click(function() {
			$(this).css('cursor', 'default').next().addClass('active').css('cursor', 'default');
			$('#delete').css('cursor', 'pointer').next().removeClass('active').css('cursor', 'pointer');
		});
		$('#delete').click(function() {
			$(this).css('cursor', 'default').next().addClass('active').css('cursor', 'default');
			$('#add').css('cursor', 'pointer').next().removeClass('active').css('cursor', 'pointer');
		});
		obj_subscribe.find(':radio:checked').click();

		var options = {
			resetForm: false,
			success: function(xml) {
				var msg = $('msg', xml).text(); var error = $('error', xml).text();
				if (error == false)
				{
					$('#subscribe-form').html('<span class="plus">'+msg+'</span>');
				}
				else {
					$('#subscribe-msg').html('<span class="ops">'+msg+'</span>');
				}
				$('#subscribe-form img.loading').hide();
			}
		};

		obj_subscribe.validate({
			submitHandler: function(form) {
				$('#subscribe-msg').empty();
				$('#subscribe-form img.loading').show();
				$(form).ajaxSubmit(options);
			},
			rules : {
				email: { email: true }
			},
			messages : {
				email: {
					email: msgWrongEmail
				}
			}
		});
		// end SUBSCRIBE FORM


		/* begin TWITTER */
		$('#twitter').getTwitter({
			userName: "PBGlobal",
			loaderText: loadingTwitts,
			slideIn: true
		});
		// follow me!!!
		$('a.followw').css({height: $('div.twittter-outer').height() - 45 });
		$('a.follow, a.followw').hover(
			function() { $('a.followw').show(); },
			function() { $('a.followw').hide(); }
		);
		/* end TWITTER */

		var obj_ul_book_li_h5 = $('ul.book li h5');
		obj_ul_book_li_h5.find('ins').show(); obj_ul_book_li_h5.find('a').hide().addClass('cufon');
		obj_ul_book_li_h5.find('ins').mouseover(function(){
			obj_ul_book_li_h5.find('a.active').removeClass('active').prev().show().next().hide();
			$(this).next().addClass('active').show().prev().hide();
		});
		obj_ul_book_li_h5.find('a.cufon').mouseout(function(){
			$(this).prev().show(); $(this).hide();
		});

		Cufon.replace('div.support ins, div.right ul.book li h5 ins, div.right ul.book li h5 a', { fontFamily: 'Myriad Pro' });

		if (bodyClass == 'news') {
			newsPages();
		}
	}
	else if (bodyClass == 'support') {
		// horizontal scroll on support-360
		if ($('div#pane').length > 0)
		{
			$('div.wp-scroll ul').width( $('div.wp-scroll ul li').length * 127);
			$('div#pane').jScrollHorizontalPane({showArrows:true, dragMinWidth:144, dragMaxWidth:144, scrollbarHeight: 16, arrowSize: 29});
		}

		// horizontal scroll on support
		var obj_support_pane = $('#support-pane');
		if (obj_support_pane.length > 0)
		{
			obj_support_pane.height('205px');
			obj_support_pane.find('ul').width(obj_support_pane.find('ul li').length * 195);
			obj_support_pane.jScrollHorizontalPane({showArrows: true, dragMinWidth: 144, dragMaxWidth: 144, scrollbarHeight: 16, arrowSize: 29});
		}
		$('div.jScrollPaneDrag').mousedown(function(){ $(this).addClass('jScrollPaneDragActive'); } );
		$('div.jScrollPaneDrag').bind('mouseup mouseout', function(){ $(this).removeClass('jScrollPaneDragActive'); } );

		supportTableCells();
		Cufon.replace('div.support ins, #support-pane ul li span', { fontFamily: 'Myriad Pro' });
	}
	else if (bodyClass == 'faq') {
		faqPages();
	}
	else if (bodyClass == 'where-to-buy')
	{
		var obj_goto = $('div.map div.goto');
		// cities dropdown
		obj_goto.find('span').click(function(event){
			event.stopPropagation();
			$(this).next().toggle();
		});
		obj_goto.find('ul li a').click(function(event){
			event.stopPropagation();
			$(this).parent().parent().hide();
		});
		$(document).click(function() { obj_goto.find('ul').hide(); });

		Cufon.replace('ul.shops li h5', { fontFamily: 'Myriad Pro' });
	}
	else
	{
		url = document.location.pathname;
		if (url == '/company/social-responsibility/')
		{
			$('div.footer a[href=/company/social-responsibility/]').addClass('active');
		}
		else if (url == '/company/career/')
		{
			$('div.footer a[href=/company/career/]').addClass('active');
		}
	}

	Cufon.replace('div.wrap h4.header, div.wrap h4.sub-header, div.wrap h4.sub-header2, div.wrap h4.sub-header3', { fontFamily: 'Myriad Pro' });

	var obj_lng_select = $('div.footer div.select');
	// languages dropdown
	obj_lng_select.find('span').click(function(event){
		event.stopPropagation();
		$(this).next().toggle();
	});
	obj_lng_select.find('ul li a').click(function(event){
		event.stopPropagation();
		$(this).parent().parent().hide();
	});
	$(document).click(function(){ obj_lng_select.find('ul').hide(); });

	// table styling
	$('table tr:even').addClass('even');
	$('table tr').hover(
		function() { $(this).addClass('over'); },
		function() { $(this).removeClass('over'); }
	);
	$('table tr').click(
		function() { $(this).toggleClass('clicked'); }
	);
	$('table tr td:first-child').addClass('firstColumn');

	// carousel on compare and product
	if ($('ul#carousel').length > 0)
	{
		$('ul#carousel').jcarousel({ easing: 'BounceEaseOut', animation: 1000 });
		$('ul#carousel li.jcarousel-item').append('<ins></ins>');
		$('ul#carousel li.jcarousel-item').hover(
			function() {
				$(this).addClass('carousel-active');
				$('#carousel_title').text($(this).find('em').text());
				$('#carousel_description').text($(this).find('span').text());
			},
			function() { $(this).removeClass('carousel-active'); }
		);
	}

	$.reject();
});

function supportTableCells()
{
	var obj_support_table_tr = $('#support-table tr');
    obj_support_table_tr.find('div div div div').height('auto');
    obj_support_table_tr.each(function(){
        var h = 0; var $this = $(this);
        $this.find('div div div div').each(function(){
            if ($(this).height() > h) h = $(this).height();
        });
        //$(this).find('div div div div').height(h);
       $this.find('div div div div').each(function(){
            var p = (h - $(this).height())/2;
            $(this).css( { paddingTop: p, height: $(this).height() + p } );
        });
    });
}

function compareTableUpdate()
{
	var obj_compare_table = $('#compare-table'); COMPARE_COUNT = 0;
	obj_compare_table.find('th span.delete').each(function(){
		$(this).attr('num', ++COMPARE_COUNT);
	});
	if (COMPARE_COUNT < 3) obj_compare_table.find('th span.delete').hide();
	else if (COMPARE_COUNT == 3)  obj_compare_table.find('th span.delete').show();

    var w = obj_compare_table.width() - obj_compare_table.find('td.firstColumn:eq(0)').width();
    obj_compare_table.find('tr td:gt(0)').width(w / (COMPARE_COUNT - 1));
	obj_compare_table.find('tr div div div div').height('auto');
    obj_compare_table.find('tr').each(function(){
        var h = 0; var $this = $(this);
        $this.find('div div div div').each(function(){
            if ($(this).height() > h) h = $(this).height();
        });
        $this.find('div div div div').height(h);
    });
}

function compareTableAdd(reader_id)
{
	var obj_compare_table = $('#compare-table');
	obj_compare_table.find('img.loading').show();
	$.get('/compare/load.compare.model/', { 'model_id': reader_id }, function(data){
		var tds = data.split('|'); var n = tds.length; var i = 0;
		obj_compare_table.find('tr').each(function(){
			$(this).append(tds[i++]);
		});
		Cufon.replace('#compare-table th a.border i', { fontFamily: 'Myriad Pro' });
		compareTableUpdate();
		obj_compare_table.find('img.loading').hide();
	});
}

function productPage()
{
	// products top tab logic
	$('ul.product-tab span').click(function(){
		$('ul.product-tab li').removeClass('active');
		$(this).parent().addClass('active');

		$('div.pr-tab').hide();
		$('#' + $(this).attr('class')).show();

		var USED = 0

		if ($(this).attr('class') == 'tab3' && USED == 0)
		{
			USED = 1;
			if ($('div.foto-small').length > 0)
			{
				//$('div.support-scroll ul').width( $('div.support-scroll ul li').length * 195);
				//$('div.foto-small>div').jScrollPane({showArrows:true, dragMinWidth:144, dragMaxWidth:144, scrollbarHeight: 16, arrowSize: 29});
				$('div.foto-small').css('overflow', 'none');
				$('div.foto-small>ul').jScrollPane({showArrows:true, dragMinHeight:144, dragMaxHeight:144, scrollbarWidth: 16, arrowSize: 29});
			}
		}
	});

	// click on colors
	var set_colors_a = $('#item-tab-contents div.columns span.colors a');
	set_colors_a.click(function(){
		var $this = $(this); var set_id = $this.find('var').text();
		$('#set'+set_id+' span.colors a').removeClass('active');
		$this.addClass('active');
		$('#img_set'+set_id).attr('src', $this.find('img').attr('src'));
		return false;
	});


	// item tabs logic
	$('ul.item-tabs li a').each(function(){
		var $this = $(this); $this.hide();
		$this.after('<span rel="'+$this.attr('rel')+'">'+$this.text()+'</span>'+'<ins rel="'+$this.attr('rel')+'">'+$this.text()+'</ins>');
	});

	if (location.hash == '#capabilities' || location.hash == '#contents' || location.hash == '#specification' || location.hash.substring(1, 4) == 'acc')
	{
		var rel = location.hash.substring(1);
		if (rel.substring(0, 3) == 'acc') { rel = 'contents'; }

		$('ul.item-tabs li span').hide();
		$('ul.item-tabs li ins').show();

		$('ul.item-tabs li ins[rel='+rel+']').hide().prev().show();

		$('div.item-tab').hide();
		$('#item-tab-'+rel).show();
	}

	$('ul.item-tabs li ins').click(function(){
		//$('ul.item-tabs li').removeClass('active');
		//$(this).parent().addClass('active');

		$("html:not(:animated),body:not(:animated)").animate({ scrollTop: $(this).offset().top - 10}, 1000);
		location.hash = $(this).attr('rel');

		$('ul.item-tabs li span').hide();
		$('ul.item-tabs li ins').show();
		$(this).hide();
		$(this).prev().show();

		$('div.item-tab').hide();
		$('#item-tab-' + $(this).attr('rel')).show();
	});

	// carousel on product for accesories
	if ($('ul#carousel-2').length > 0)
	{
		$('ul#carousel-2').jcarousel({ easing: 'BounceEaseOut', animation: 1000 });
		$('ul#carousel-2 li.jcarousel-item').append('<ins></ins>');
		$('ul#carousel-2 li.jcarousel-item').hover(
			function() {
				$(this).addClass('carousel-active');
				$('#accessory_title').text($(this).find('em').text());
			},
			function() { $(this).removeClass('carousel-active'); }
		);
		$('ul#carousel-2 li.jcarousel-item').click(function(e) {
			e.preventDefault();
			location.hash = 'contents';

			$('ul.item-tabs li span').hide();
			$('ul.item-tabs li ins').show();
			$('ul.item-tabs li ins[rel=contents]').hide().prev().show();

			$('div.item-tab').hide();
			$('#item-tab-contents').show();

			$('html:not(:animated),body:not(:animated)').animate({ scrollTop: $('#accessories').offset().top - 10}, 1000);
		});
	}

	var params = {}; var flashVars = {}; var attributes = {};
	if ($('#promo').length > 0 && $('#promo').attr('url') != '')
	{
		params = {wmode:"transparent", allowScriptAccess:"always" };
		attributes = {};
		attributes.id = "promo";
		attributes.styleclass = "promo";
		swfobject.embedSWF($('#promo').attr('url'), "promo", "783", "381", "9.0.115", "/swf/expressInstall.swf", {}, params, attributes);
	}

	if ($('#threeDViewer').length > 0 && $('#threeDViewer').attr('url') != '')
	{
		params = {wmode:'transparent', allowScriptAccess:'always' };
		flashVars = { dataPath: $('#threeDViewer').attr('url'), uiPath: $('#threeDViewer').attr('ui') };
		attributes = {};
		attributes.id = "threeDViewer";
		attributes.styleclass = "threeDViewer";
		swfobject.embedSWF("/swf/3DViewer.swf", "threeDViewer", "783", "381", "10.0.42", "/swf/expressInstall.swf", flashVars, params, attributes);
	}

	$.preloadImages = function() {
		for(var i = 0; i<arguments.length; i++){
			$('<img>').attr('src', arguments[i]);
		}
	};

	$('div.foto-small ul li a').click(function(){
		var photo = $(this).attr('href');
		if (photo != $('div.foto img').attr('src'))
		{
			$.preloadImages(photo);

			  $('div.foto img').animate({ opacity: 0 }, 500, function() {
					$(this).attr('src', photo).animate({opacity: 1}, 500);
			  });

			$('div.foto-small ul li a').removeClass('active');
			$(this).addClass('active');
		}
		return false;
	});

	$('ul#accessories li a[rel=lightbox]').lightBox({fixedNavigation:true});

	Cufon.replace('ul.item-tabs>li>span, ul.item-tabs>li>ins, div.wrap ul.access li h4', { fontFamily: 'Myriad Pro' });
}//function productPage()

/* begin NEWS PAGES */
function loadNews(xml)
{
	document.title = $('content page-title', xml).text();
	$('div.header div.path').html($('content page-legend', xml).text());
	$('ul.news').html($('content news-list', xml).text());
	$('ul.paging').html($('content pages-list', xml).text());
	$('ul.news-tabs li img').hide();
	newsLogic();
}

function newsPages()
{
	// news tabs logic
	var obj_ul_news_tabs_li = $('ul.news-tabs li');
	obj_ul_news_tabs_li.find('a').each(function(){
		$this = $(this); $this.hide();
		$this.after('<span>'+$this.text()+'</span>'+'<ins rel="'+$this.attr('rel')+'">'+$this.text()+'</ins>'+IMG_LOADING);
	});
	obj_ul_news_tabs_li.find('ins').click(function(){
		obj_ul_news_tabs_li.removeClass('active');
		$this = $(this); var url = $this.attr('rel'); location.hash = url;
		$this.parent().addClass('active').find('img.loading').show();
		$.get('/news/load.news/', { 'url': url 	}, loadNews);
	});

	if (location.hash != '')
	{
		var rel = location.hash.substring(1);
		obj_ul_news_tabs_li.removeClass('active');
		obj_ul_news_tabs_li.find('ins[rel='+rel+']').parent().addClass('active').find('img.loading').show();
		$.get('/news/load.news/', { 'url': rel }, loadNews);
	}

	newsLogic();
	Cufon.replace('ul.news-tabs>li>span, ul.news-tabs>li>ins', { fontFamily: 'Myriad Pro' });
}

function newsLogic()
{
	var obj_ul_news_li = $('ul.news li');
	obj_ul_news_li.find('span').show(); obj_ul_news_li.find('a.title').hide().removeClass('title').addClass('cufon');
	obj_ul_news_li.find('span').mouseover(function(){
		obj_ul_news_li.find('a.active').removeClass('active').prev().show().next().hide();
	    $(this).next().addClass('active').show().prev().hide();
	});
	obj_ul_news_li.find('a.cufon').mouseout(function(){
		$(this).prev().show(); $(this).hide();
	});

    $('ul.paging li a').click(function(e){
		e.preventDefault();
		var url = $('ul.news-tabs li.active ins').attr('rel');
		$('ul.news-tabs li.active img.loading').show();
		location.hash = url;
		$.get('/news/load.news/', { 'url': url, 'p': $(this).attr('rel') }, loadNews);
	});

    Cufon.replace('ul.news>li>span, ul.news>li>ins, ul.news>li>a', { fontFamily: 'Myriad Pro' });
}
/* end NEWS PAGES */

/* begin FAQ PAGES */
function faqPages()
{
	$('div.footer a[href=/support/faq/]').addClass('active');

	// faq question logic
	var obj_ul_faq_li = $('ul.faq li');
	obj_ul_faq_li.find('span').each(function(){
		$this = $(this); $this.after('<ins>'+$this.text()+'</ins>');
	});

	$('#faq textarea').val('');

	obj_ul_faq_li.find('>div').hide();
	obj_ul_faq_li.find('span').hover(function()
	{
		obj_ul_faq_li.not('.active').find('ins:visible').hide().prev().show();
		$(this).next().show().prev().hide();
	});

	obj_ul_faq_li.find('ins').bind('mouseleave', function(){
		obj_ul_faq_li.not('.active').find('ins:visible').hide().prev().show();
	});

	obj_ul_faq_li.find('ins').click(function(){
		var $this = $(this); var show = true;
		show = !$this.parent().hasClass('active');

		obj_ul_faq_li.removeClass('active').find('>div').slideUp(200);

		if (show)
		{
			$this.parent().addClass('active');
			$this.next().slideDown(200);
			obj_ul_faq_li.not('.active').find('ins:visible').hide().prev().show();
		}
	});

	obj_ul_faq_li.find('div.help a').click(function(){
		$this = $(this);
		$.get('/faq/vote/', { 'question_id' : $this.attr('rel'), 'value' : $this.attr('value') }, function(){
			$this.parent().html(msgThanks);
		});
		return false;
	});

	if (!$.browser.msie) {
		Cufon.replace('div.left ul.faq li b, div.left ul.faq li span, div.left ul.faq li ins', { fontFamily: 'Myriad Pro' });
	}

	var obj_faq = $('#faq');
	// faq inputs
	obj_faq.find('input:eq(0)')
	.focus(function(){ if ($(this).val() == formName) $(this).val('').css('color', '#221E1F'); })
	.blur(function(){ if ($(this).val() == '') $(this).val(formName).css('color', '#737373'); });
	obj_faq.find('input:eq(1)')
	.focus(function(){ if ($(this).val() == formEmail) $(this).val('').css('color', '#221E1F'); })
	.blur(function(){ if ($(this).val() == '') $(this).val(formEmail).css('color', '#737373'); });
	obj_faq.find('textarea')
	.focus(function(){ if ($(this).val() == formMessage) $(this).val('').css('color', '#221E1F'); })
	.blur(function(){ if ($(this).val() == '') $(this).val(formMessage).css('color', '#737373'); });
	obj_faq.find('input.submit').after(IMG_LOADING);

	// begin FAQ FORM
	var options = {
		resetForm: true,
		success: function(data) {
			$('div.faq').find('span.fill').html(data).parent().find('#faq').hide();
		}
	};
	obj_faq.validate({
		submitHandler : function(form) {
			$(form).find('img.loading').show();
			$(form).ajaxSubmit(options);
		},
		rules : {
			name : 'required',
			email : { email : true },
			message : 'required'
		},
		messages : {
			name : {
				required : msgNameRequired
			},
			email: {
				email: msgWrongEmail
			},
			message : {
				required : msgMessageRequired
			}
		}
	});
	// end FAQ FORM

	Cufon.replace('div.right div.faq h5', { fontFamily: 'Myriad Pro' });
}
/* end FAQ PAGES */