(function ($) {
	$.fn.vAlign = function() {
		return this.each(function(i){
			$(this).children().wrapAll('<div class="nitinh-vAlign" style="position:relative;"></div>');
			var div = $(this).children('div.nitinh-vAlign');
			var ph = $(this).innerHeight();
			var dh = div.height();
			var mh = (ph - dh) / 2;
			div.css('top', mh);
		});
	};
})(jQuery);

function parse_url (str, component) {
    // Parse a URL and return its components  
    // 
    // version: 1109.2015
    // discuss at: http://phpjs.org/functions/parse_url    // +      original by: Steven Levithan (http://blog.stevenlevithan.com)
    // + reimplemented by: Brett Zamir (http://brett-zamir.me)
    // + input by: Lorenzo Pisani
    // + input by: Tony
    // + improved by: Brett Zamir (http://brett-zamir.me)    // %          note: Based on http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js
    // %          note: blog post at http://blog.stevenlevithan.com/archives/parseuri
    // %          note: demo at http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js
    // %          note: Does not replace invalid characters with '_' as in PHP, nor does it return false with
    // %          note: a seriously malformed URL.    // %          note: Besides function name, is essentially the same as parseUri as well as our allowing
    // %          note: an extra slash after the scheme/protocol (to allow file:/// as in PHP)
    // *     example 1: parse_url('http://username:password@hostname/path?arg=value#anchor');
    // *     returns 1: {scheme: 'http', host: 'hostname', user: 'username', pass: 'password', path: '/path', query: 'arg=value', fragment: 'anchor'}
    var key = ['source', 'scheme', 'authority', 'userInfo', 'user', 'pass', 'host', 'port',                         'relative', 'path', 'directory', 'file', 'query', 'fragment'],
        ini = (this.php_js && this.php_js.ini) || {},
        mode = (ini['phpjs.parse_url.mode'] && 
            ini['phpjs.parse_url.mode'].local_value) || 'php',
        parser = {            php: /^(?:([^:\/?#]+):)?(?:\/\/()(?:(?:()(?:([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?()(?:(()(?:(?:[^?#\/]*\/)*)()(?:[^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
            strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
            loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/\/?)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ // Added one optional slash to post-scheme to catch file:/// (should restrict this)
        };
     var m = parser[mode].exec(str),
        uri = {},
        i = 14;
    while (i--) {
        if (m[i]) {          uri[key[i]] = m[i];  
        }
    }
 
    if (component) {        return uri[component.replace('PHP_URL_', '').toLowerCase()];
    }
    if (mode !== 'php') {
        var name = (ini['phpjs.parse_url.queryKey'] && 
                ini['phpjs.parse_url.queryKey'].local_value) || 'queryKey';        parser = /(?:^|&)([^&=]*)=?([^&]*)/g;
        uri[name] = {};
        uri[key[12]].replace(parser, function ($0, $1, $2) {
            if ($1) {uri[name][$1] = $2;}
        });    }
    delete uri.source;
    return uri;
}

$(function() {
	

	if($('#enquiry_form').length > 0)
	{
		$('#enquiry_form form').submit(function(e) {
			e.preventDefault();
			var url = parse_url(window.location.pathname);
			url = url.path;
			$.ajax({
				url: '/enquiryFormProcess/',
				type: 'post',
				dataType: 'json',
				data: $('#enquiry_form form').serialize() + '&eq_product_url=' + url,
				success: function(r) {
					if(r.status == 'fail') {
						if(r.errors.length) {
							$.each(r.errors, function(){
								if(this.key == 'eq_form_interest') {
									var e = $('#enquiry_form form input[name=' + this.key + ']');
									$('div.errMsg',e.parent().parent()).text(this.message).fadeIn();
									e.parent().parent().addClass('error');							
								}else{
									var e = $('#enquiry_form form input[name=' + this.key + ']');
									e.parent().addClass('error');
									$('div.errMsg',e.parent()).text(this.message).fadeIn();
								}
							});
						} else {
							$('#enquiry_form form').fadeOut(function(){
								$('#enquiry_form').html('<div class="error">Something went wrong whilst posting your enquiry, please use our contact form or contact us by phone</div>');
							});
						}
					} else {
						$('#enquiry_form form').fadeOut(function(){
							$('#enquiry_form').html('<div class="success">' + r.message + '</div>');
						});
					}
				}
			});
		});
	}

	// round the corners in a less DOM intensive way
	// leaves IE6, coz' its bad
	if (!jQuery.browser.msie || jQuery.browser.version > 6) {
		$('#menu ul li a, #menu ul li em, blockquote, #menu ul li em.conference, #menu ul li a.conference, div#midWrap').each(function() {
							if ($(this).children('span.tr, span.bl, span.br, span.tl, #menu ul li a, #menu ul li em, #content.about-fairtrade div.block blockquote').length == 0) {
								$(this).prepend('<span class="tr">&nbsp</span>')
									   .prepend('<span class="tl">&nbsp</span>')
									   .append('<span class="bl">&nbsp</span>')
									   .append('<span class="br">&nbsp</span>');
								if (this.tagName.toLowerCase() === 'blockquote') {
									$(this).append('<span class="thing">&nbsp;</span>');
								}
							}
						});
    $('div.block').each(function(){
           $(this).prepend('<span class="tr">&nbsp</span>')
                  .prepend('<span class="tl">&nbsp</span>')
                  .append('<span class="bl">&nbsp</span>')
                  .append('<span class="br">&nbsp</span>');   
    });

        $('div#menu').prepend('<span class="left">&nbsp;</span>').append('<span class="right">&nbsp;</span>');
	}
	// fudge target _blank to all external links, to make page validate
	$('a').each(function() {
		if ($(this).attr('class') === 'external') {
			$(this).attr('target', '_blank');
		}
	});

	$('div.error, div.notice, div.success').each(function() {
		$(this).css('display', 'none');
		$(this).fadeIn("slow");
	});

	$('div#imageSwitcher ul').innerfade( {
		timeout : 3500,
		speed : 2000
	});

	$('div#content.office-supplies div div.block.first ul li p span.expander')
			.each(function() {
				$(this).css('display', 'none');
			});

	var equalHeight = function() {
		if($('div#content').hasClass('twoCols2') || $('div#content').hasClass('twoCols')) {
			$('div.line').each(function(){
				tallest = 0;
				$('.block', this).each(function(){
					thisHeight = $(this).height();
					if(thisHeight > tallest) {
						tallest = thisHeight;
					}
				});
				$('.block', this).css('cssText', 'min-height:' + tallest + 'px !important; height: auto; height: ' + tallest + 'px');
				tallest = 0;
			});
		}else{
		    group = $('div#content div.col-1 div.block, div#content div.col-2 div.block, div#content div.block, div#content div.block');
		    tallest = 0;
		    $(group).each(function() {
		        thisHeight = $(this).outerHeight();
		        if(thisHeight > tallest) {
		            tallest = thisHeight;
	        	}
		    });
		    $(group).css('cssText', 'min-height:' + tallest + 'px !important; height: auto; height: ' + tallest + 'px');
		}
	};//self invoking
	equalHeight();

	$('div#content div div.block.first ul li p a.expandLink')
			.click(function(event) {
				
				$(this).css('display', 'none');
				$('+span.expander', this).fadeIn("slow");
				equalHeight();
				event.preventDefault();
				return false;
			});
		count = 1;
			/*$('#phoneDetails #phoneDetailsTextEffect b').text($('#phoneDetails #phoneDetailsTextEffect b').text().replace(/\s/g, ''));
	        $("#phoneDetails #phoneDetailsTextEffect").html(jQuery.map( $("#phoneDetails #phoneDetailsTextEffect b").html().split(""), function(letter){
        		return "<b style=\"display: inline\">" + letter + "</b>";
	        }).join(""));
	        $("#phoneDetails #phoneDetailsTextEffect b").each(function(i, letter){
	        	if(i === 4 || i === 7){$(letter).css('margin-right','5px');}
	        	defaultCol = $(letter).css('color');
	        });
	        
	    setInterval(function(){
	        $("#phoneDetails #phoneDetailsTextEffect b").each(function(i, letter){
	            setTimeout(function(){
	                tcolor = (count % 2) ? defaultCol : 'red';
	                $(letter).animate({color: tcolor}, 1000);
	            }, i * 100);
	        });
	     ++count;
	   }, 5000);
*/
       $('p.payment_module a').click(function(e){
         if($('div#fl_section_shipping').length){
          if(!$('input[type=radio]:checked').length){
            alert('Please select a shipping option');
            e.preventDefault();
          }else {
            $('form#paypal_form').submit();
          }
        }else{
          $('form#paypal_form').submit();
        }});

        $('ul.tree li').each(function(){
    		var currentId = parseInt($(this).parent().parent().attr('class').replace('block_content categories selectedId-', ''));
        	var catId = parseInt($('a', this).attr('class').replace('selected', '').replace('catId-', ''));
        	var $li = $(this);	
        	if(catId === currentId){
        		getCats(catId, $li);
        	}else{
       			parentId = getParent(currentId);
	       		if(parentId > 1 && parentId == catId){
	       			getCats(parentId, $li);
	       			$('ul li a', $li).each(function(){
	       				if($(this).attr('class').replace('catId-', '') == currentId){
	       					$(this).addClass('selected');
	       				}
	       			})
	       		}
        	}
        });
	function updateDummy(){
		$('#dummy_price span.our_price_display').html($('form#buy_block p.price span.our_price_display').html().replace('our_price_display', 'dummy_our_price_display').replace('pretaxe_price_display', 'dummy_pretaxe_price_display'));
		$('#avail').html($('#availability_value').text());
		if($('#availability_value').text().toLowerCase() == 'the product does not exist in this model. please choose another.'){
			$('#dummy_submit').hide();
		}else{
			$('#dummy_submit').show();
		}
	}
	$('#quantity_wanted').keyup(function(){
		$('#dummy_quantity_wanted').val($('#quantity_wanted').val());
		updateDummy();
	});
	$('#attributes select').change(function(){
		$('#dummy_attributes select.' + $(this).attr('id')).val($(this).val());
		updateDummy();
	});
    if($('#dummy_price').length){
    	setTimeout(function(){updateDummy()}, 500);
    }
	$('#dummy_attributes select').change(function(){ 
		var id = $(this).attr('class');
		$('#' + id).val($(this).val());
		findCombination();
		updateDummy();
	});
	$('#dummy_quantity_wanted').keyup(function(){
		$('#quantity_wanted').val($(this).val());
	});
	$('#dummy_submit').click(function(e){
		e.preventDefault();
		$.scrollTo('#page', 500);
		ajaxCart.add( $('#product_page_product_id').val(), $('#idCombination').val(), true, null, $('#quantity_wanted').val(), null);
		return false;
	});
});
/* This is a fudge of an order of magnitude to that of a global thermo-nuclear war */
$.globals = {cachedParentId : false};
function getCats(id, inject){
	$('<div style="font-size: 0.5em; font-weight: normal; font-family: arial; color: grey; margin-left: 9px; position: absolute; right: 14px; top: 13px;"><img src="/images/ajaxloader.gif" style="position: relative; top: 4px"/>Loading menu items</div>').appendTo('div#categories_block_left h2');
	$('div#categories_block_left h2 div').fadeIn()
	$.ajax({
		type: 'get',
		url: '/shop/modules/blockjurangcategories/blockjurangcategoriesajax.php',
		data: {catid: id},
		dataType: 'json',
		async: false,
		success: function(data){
			$('div#categories_block_left h2 div').fadeOut();
			if(data.length > 0){
				var html = '<ul>';
				for(var i=0;i<data.length;++i){
					html += '<li><a class="catId-'+data[i].id_category+'" href="/shop/'+data[i].id_category+'-'+data[i].link_rewrite+'">'+data[i].name+'</a></li>';
				}    
				html+='</ul>';
				$(inject).append(html);
			}
		}
	});
}

function getParent(id){
if(isNaN(id)) { return; }
	if($.globals.cachedParentId == false){
		$.globals.cachedParentId = $.ajax({
		type: 'get',
		url: '/shop/modules/blockjurangcategories/blockjurangcategoriesajax.php',
		data: {getparent: 1, catid: id},
		datatype: 'text',
		async: false
	}).responseText;
	}
	return $.globals.cachedParentId;
}

