//use the mimified version, please
$(document).ready(function(){
	$('#page_footer_toggle').click(function(){
		$('#page_footer_mini').toggle('fast');
		$('#page_footer_content,#page_footer_addresses,#page_footer_search').toggle('slow');
		if($(this).hasClass('open')){$(this).removeClass('open');}else{$(this).addClass('open');}
	});
	//left menu behaviour
		//state of info display
	   	Sections = new Array('analysis','development','production');
	   	Neutrals = new Array('about','events','order','news','contact');
	   	cSection = $.cookie('section');
	   	$('.to_production').click(function(){$.cookie('section','production',{'path':'/'});});
			cUrl = window.location.toString();
	    isSection = in_array(cSection,Sections);
	    hasSection = isset(cSection);
/*	  
			cNeutral = false;

	   	for (n = 0; n < Neutrals.length; n++){
	    	if (cUrl.indexOf('/'+Neutrals[n]+'/') > 0){cNeutral = true;}
	    }
	   	if(!cNeutral || isSection){$("#page_menu p").hide();
*/
	  if(isSection || hasSection){$("#page_menu p").hide();}
		$('#page_menu li a').each(function(){
			if(cUrl.indexOf($(this).attr('href')) > 0){$(this).parent().addClass('on');}		
		});
		//highlight current position
		$('#header_navigation li a').each(function(){
			if(cUrl.indexOf($(this).attr('href')) > -1){$(this).parent().addClass('on');}		
		});
		$('.pagelinks li a').each(function(){
			if(cUrl.indexOf($(this).attr('href')) > -1){$(this).parent().addClass('on');}		
		});
	//
	//stripe zebra tables
		zebraStriping();
	//
	$('.fig').each(function(){
		figDiv = $(this);
		figWidth = figDiv.children('img:first').width();
		figDiv.css('width',figWidth*1.0);
	});
	$('.page_content_image_head').next('h2, h3, h4, p, ul').addClass('below_header');
	//cart actions
	$('.zero').hide().removeClass('hidden');
	$('.cart input').change(function(){
		inputId = $(this).attr('id');
		inputVal = $(this).val();
		itemId = inputId.substring(2);
		thisRow =$(this).parents('tr');
		$.get('/my/actions/cart.php',{'selection': itemId, 'qty': inputVal}, function(data){
			$.gritter.add({
				title: 'Selection notification',
				text: data
			});
			if(inputVal == 0){
				thisRow.addClass('deleted');
				UpdateSelectionCount();
			}
		});
	});
	$('.cart a[class!="dl"]').click(function(){
		oldUrl = $(this).attr('href');
		thisInput =$(this).parents('tr').find('input');
		thisRow =$(this).parents('tr');
		newUrl = '/my/actions/cart.php' + oldUrl.substring(oldUrl.indexOf('?'));
		$.get(newUrl,{},function(data){
			$.gritter.add({
				title: 'Selection notification',
				text: data
			});
		});
		oldValue = parseInt(thisInput.val());
		if(oldUrl.indexOf('=incr')>0){
			thisInput.val(oldValue + 1);
			if(oldValue == 0){
				thisRow.removeClass('deleted');
				UpdateSelectionCount();
			}
		}
		if(oldUrl.indexOf('=decr')>0){
			thisInput.val(oldValue - 1);
			if(oldValue == 1){
				thisRow.addClass('deleted');
				UpdateSelectionCount();
			}
		}
		if(oldUrl.indexOf('=0')>0){
			thisInput.val(0);
			thisRow.addClass('deleted');
			UpdateSelectionCount();
		}
		return false;
	});

	$('.fieldset_list_old').find('input,textarea')
		.focus(function(){$(this).next('span.tooltip').addClass('tooltip_on');})
		.blur(function(){$(this).next('span.tooltip').removeClass('tooltip_on');});
	$('.tipsa')
		.mouseover(function(){
			var obj = $(this);
			var tool = obj.next('span.tooltip');
			var w = obj.offset().left;
			var h = obj.offset().top;
			var dw = obj.width(); // + 
			var dh = obj.height(); //obj.offset().top + 
			console.info('w=' + w + ', h=' + h + ', dw=' + dw + ', dh=' + dh);
			tool.addClass('tooltip_over');
			tool.css({left : 350 , top : dh});
		})
		.mouseout(function(){$(this).next('span.tooltip').removeClass('tooltip_over');});
	if(jqt == true){//jquery.tools is loaded
		$("ul.tabs").tabs("div.panes > div.pane",{
		}).history();
	}
	//$('ul.addresstabs a').click();
	$('div.addresspanes').show();
	$('div.addresspanes>div.addresspane:first').show();
	if(fb == true){
		$('#page_content a.prod_info').fancybox({
	    	'hideOnContentClick' : false,
	    	'overlayOpacity' : 0.3,
	    	'padding' : 0,
	    	'frameWidth' : 350,
	    	'frameHeight' : 230,
	    	'overlayShow' : true,
	    	'callbackOnStart' : checkShift()
	    });
	}
	$('#countryId').change(function(){
		var country_id = $(this).val();
		var toggle_status = '';
		toggle_status = $('#toggle_status:checked').val();
		if(toggle_status == 'all'){
			$.get('ajax/get_distributors.php',{'id':country_id,'s':toggle_status}, function(data){
				$('#country_distributors').html(data);
				toggleDistMap(country_id);
			});
		}else{
			$.get('ajax/get_distributors.php',{'id':country_id}, function(data){
				$('#country_distributors').html(data);
				toggleDistMap(country_id);
			});
		}
	});
	$('.country').click(function(){
		var country_id = $(this).attr('id');
		var toggle_status = '';
			if($('#toggle_status_all').prop('checked') == true){toggle_status = toggle_status + 'all';}
			if($('#toggle_status_mine').prop('checked') == true){toggle_status = toggle_status + 'mine';}
			if(status != ''){status = '?status=' + status;}
		if(toggle_status != ''){
			$.get('ajax/get_distributors.php',{'id':country_id,'s':toggle_status}, function(data){
				$('#country_distributors').html(data);
				$('#countryId').val(country_id);
				toggleDistMap(country_id);
			});
		}else{
			$.get('ajax/get_distributors.php',{'id':country_id}, function(data){
				$('#country_distributors').html(data);
				$('#countryId').val(country_id);
				toggleDistMap(country_id);
			});
		}
		return false;
	});

	$('#faq').find('dd').hide().end().find('dt').click(function(){
		if ( $(this).is('.minus') ){
			$(this).removeClass('minus');
		}else{
			$(this).addClass('minus');
			$(this).addClass('visited');
		}
		$(this).next().slideToggle();
	});
	$('.protocol > li:nth-child(odd)').addClass('odd');
	
	$('a[href$=".pdf"]').click(function(){window.open(this.href);return false;});
	$('a[rel="document"]').click(function(){window.open(this.href); return false;});
	$('a[rel="external"]').click(function(){window.open(this.href); return false;});
	
	//competitor comparators on Diol and Phenyl pages
	$('#competitor_submit').hide();	
	$('#competitor_select').change(function(){$('#comparator div.competitor img').attr('src','images/' + $(this).val() + '.gif');});
	//front page
	$('a.reveal').click(function(){
		$(this).hide();
		$(this).prev('div.init').removeClass('init');
		/* $(this).prev('div.init').animate({height:'auto'},5000); */
		return false;
	});
	var distMap = $.cookie('dist_map');
	if(distMap == 'eu'){
		$('#world').hide();	
	}else{
		$('#europe').hide();	
	}
	
	$('#eu').click(function(){
		$.cookie('dist_map','eu');
		$('#europe').fadeIn(1000);
		return false;
	});
	$('#row').click(function(){
		$.cookie('dist_map','row');
		$('#europe').fadeOut(1000);
		$('#world').fadeIn(1000);
		return false;
	});
});
$(window).load(function(){
	$('#page_footer_content,#page_footer_addresses,#page_footer_search').hide().removeClass('invisible');
});
function addToTitle(titleExtention){
	if(document.title.indexOf('KromaNews')>0){
		document.title = document.title + ':' + titleExtention;
	}else{
		document.title = document.title + ': ' + titleExtention;
	}
}
function zebraStriping(){
	$('table.zebra tbody > tr:odd').addClass('odd');
	$('table.zebra1 tbody > tr:odd > td:nth-child(1)').addClass('odd');
	$('table.zebra1 tbody > tr:even > td:nth-child(1)').addClass('even');
	$('table.zebra2 tbody > tr:odd > td:nth-child(2)').addClass('odd');
	$('table.zebra2 tbody > tr:even > td:nth-child(2)').addClass('even');
	$('table.zebra3 tbody > tr:odd > td:nth-child(3)').addClass('odd');
	$('table.zebra3 tbody > tr:even > td:nth-child(3)').addClass('even');
	$('table.zebra4 tbody > tr:odd > td:nth-child(4)').addClass('even');
	$('table.zebra4 tbody > tr:even > td:nth-child(4)').addClass('odd');
}
function zebraStripingFor(tableId){	
	$('#'+tableId+' tbody > tr:odd').addClass('odd');
	if($('#'+tableId).hasClass('zebra1')){
		$('#'+tableId+' tbody > tr:odd > td:nth-child(1)').addClass('odd');	
		$('#'+tableId+' tbody > tr:even > td:nth-child(1)').addClass('even');
	}
	if($('#'+tableId).hasClass('zebra2')){
		$('#'+tableId+' tbody > tr:odd > td:nth-child(2)').addClass('odd');	
		$('#'+tableId+' tbody > tr:even > td:nth-child(2)').addClass('even');
	}
	if($('#'+tableId).hasClass('zebra3')){
		$('#'+tableId+' tbody > tr:odd > td:nth-child(3)').addClass('odd');	
		$('#'+tableId+' tbody > tr:even > td:nth-child(3)').addClass('even');
	}
	if($('#'+tableId).hasClass('zebra4')){
		$('#'+tableId+' tbody > tr:odd > td:nth-child(4)').addClass('odd');	
		$('#'+tableId+' tbody > tr:even > td:nth-child(4)').addClass('even');
	}
}
function checkShift(){
}
//Cart functions
function initCartActions(){
	//window.alert('init');
	$('.add_selection').on('click',function(){
		var thisButton = $(this);
		var ecode = thisButton.attr('title');
		//window.alert('click');
		var actionUrl = '/my/actions/add.php'; //?selection='+$(this).attr('title');
		$.get(actionUrl,{'selection': ecode},function(data){
					//$('#action_response').html(data);
				$.gritter.add({
						title: 'Selection notification',
						text: data
				});
		});
		UpdateSelectionCount();
		thisButton.hide();
		$('.done').removeClass('hidden');
		return false;
	});
	$('.add_favorite').click(function(){
		var actionUrl = '/my/actions/add.php?favorites='+$(this).attr('value');
		$.get(actionUrl,{},function(data){
			//$('#action_response').html(data);
			$.gritter.add({
				title: 'Favorite notification',
				text: data
			});
		});
		UpdateSelectionCount();
		return false;
	});
}
function initCartActionsA(){
	$('.add_selection').click(function(){
	$.get($(this).attr('href'),{},function(data){
				//$('#action_response').html(data);
			$.gritter.add({
					title: 'Selection notification',
					text: data
			});
	});
	UpdateSelectionCount();
	return false;
	});
	$('.add_favorite').click(function(){
		$.get($(this).attr('href'),{},function(data){
			//$('#action_response').html(data);
			$.gritter.add({
				title: 'Favorite notification',
				text: data
			});
		});
		UpdateSelectionCount();
		return false;
	});
}
function UpdateSelectionCount(){
	$.get('/my/actions/menu.php',{},function(data){
		$('#my-selection-wrapper').html(data);
		if($('#selection-count').html() > 0){
			$('.zero').slideDown().removeClass('zero');
		}else{
			$('#my-selection').addClass('zero').removeClass('hidden');
		}
	});
}
function toggleDistMap(id){
	$('#maps a[class~="selected"]').removeClass('selected');
	$('#'+id).addClass('selected');
}
//general functions
function isset(x){ if ((x == undefined) || ((x.toString()).toUpperCase() == 'NULL')){return false;}else{return true;} }
function in_array(needle, haystack){
	var key = '';
	for(key in haystack){if(haystack[key] == needle){return true;}}
	return false;
}
function str_replace_pos(needle,haystack,pos){
	pre = haystack.slice(0,pos);
	post = haystack.slice(pos+1);
	return pre+needle+post;
}
function strtoid(mystring){
	return mystring.replace(' ','_').toLowerCase();
}
//plugins

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
