$(function(){

	/* IE 7 and 8 might give an agent string as if it was IE6. You couldn't buy this level of incompetence! Possible fix: */
	$.browser.version = $.browser.msie && parseInt($.browser.version) == 6 && window["XMLHttpRequest"] ? '7.0' : $.browser.version;
	if($.browser.msie && $.browser.version<7)
	{
		/* lte ie6 warnings */
		var IE6UPDATE_OPTIONS={icons_path:'/_cp.nover/src/ie6update/images/'};
		$.getScript("/_cp.nover/src/ie6update/ie6update.js", function(){
		  $('<div></div>').html(IE6UPDATE_OPTIONS.message || 'Internet Explorer is missing updates required to view this site. Click here to update... ')
		  .activebar(IE6UPDATE_OPTIONS);
		  $(document.body).activebar.show();
		});
		$.get('/_cp.nover/src/ie6/ie6.html',function(d){$('#page').prepend(d)});
	}


	var anch='';
	try{
	   var parentDomain = parent.location.href;
	   inDomain=true;
	}catch(e){
	   inDomain=false;
	}
	if (inDomain) anch=parent.document.URL.split("#")[1];
	

	// resize resized prlist images.
	$('.m-prodlist .im img').each(function(){
		if ($(this).width()>200) $(this).attr('src',$(this).attr('src').replace('_125.','_300.').replace('--125.','--300.').replace('!s=125','!s=300').replace('width=125','width=300').replace('height=125','height=300'));
	});

	$('.m-prodlist li').each(function(){
		var bicon=$(this).find('.biconcp:is(visible)');
		if (bicon)
		{
			bicon.css({opacity:0});
			$(this).bind('mouseenter',function(){
				$(this).find('.biconcp').stop().animate({opacity:1},300);
			}).bind('mouseleave',function(){
				$(this).find('.biconcp').stop().animate({opacity:0},300);
			});
		}
	});

	$.nyroModalSettings({autoSizable:true, minHeight:50, css:{overflow:'visible'}});
	cpLoadUserMenu();
	cpLoadEnquiryListLastUpdated=new Date();

	if ($('#msg').html()!='')
	{
		$.nyroModalManual({
			content:$('#msg').html()
			, endShowContent:function(){$('#msg').html(' ');}
		});
	};
	
	
	$('.m-catlist-showhide').click(function(){
		$(this).find('span,em').toggle();
		$(this).parent().find('.m-catlist-list').toggle();
	});
	if ($('.m-catlist-list').is(':visible')) $('.m-catlist-showhide span, .m-catlist-showhide em').toggle(); /* if cats are open, switch the showhide, it's set to say "Show" by default */

	$('.autotitle').titleInValue();
/*	$('.m-prodlist li .im').cpprodpop();  */
	
	$('.prod-image-click').nyroModal();
	$('.m-prodlist-enquirylist li').each(function(){
		var el=$(this);
		$(this).find('input,select').bind('change',function(){cpInterruptNav('enquiry');});
		$(this).find('.icon-enquiry-remove').click(function(e){
			e.preventDefault();
			cpInterruptNav('enquiry');
			el.find('input.prodenqqty').val(-1);
			el.css('opacity',0.3);
			el.slideUp(500);
		});
	});
	$('.icon-enquiry-add').click(function(e){
		e.preventDefault();
		el=$(this);
		el.addClass('icon-loading');
		$.get($(this).attr('href')+'&inc=a',function(d){
			el.removeClass('icon-loading');
			if (d!=undefined)
			{
				data=d.split('|');
				if (data[1]=='quick') 
				{
					cpLoadUserMenu();
				}
				else
				{
					$.nyroModalManual({
						closeButton:''
						, content:data[1]
						, endShowContent:function(){cpBindEnquiryQMQForm();}
					});
				}
			}
		});
	});
	
	addRemoveFav();
	
	$('#logo-upload-button').click(function(){
		$.nyroModalManual({
			url: 'index.php?inc=a&go=logo-upload&do=loadform'
			, autoSizable : true
			, endShowContent:function(){/*
				$('#logofromwebbutton').click(function(){
					cp_logoFromWebsite($('#logofromweb').val());
			   });
				*/
			}
		});
		/*
		$('#logo-upload-form').ajaxForm({
			beforeSubmit: function(a,f,o) {
				o.dataType = 'html'
				$.nyroModalManual({contents:'Uploading...'});
			}
			,
			success: function(data) {
			}
		});
		*/
    });
	
	
	

	/* done via ajax.
	$('#enquiryForm').submit(function(){cpInterruptNav(false);
		$(this).validate();

		if(typeof (window.validateEnquiryForm) == 'function') {
				 return validateEnquiryForm();
		}
	});*/
	
	$('.formsend').each(function(){
		var formsend=$(this);
		var form=$(this).find('form');
		var form_id=$(this).find('input[name="form_id"]').val();
		/* prepare for ajax submission */
		form.attr('action','/index.php').find('input[name="go"]').attr('value','form.respond');
		$('<input type="hidden" name="inc" value="a" />').appendTo(form);
		form.ajaxForm({
			beforeSubmit:function(){
				form.find('.error').remove();

			}
			,success:function(d){
				data=d.split('|');
				if (data[0]=='f')
				{
					var errors=data[1].split("\n\n");
					for (i in errors)
					{
						var bits=errors[i].split(':');
						var id=bits.shift();
						var html=bits.join(':');
						$('#errorfor_'+id).html(html);
					}
				}
				else
				{
					form.hide();
					$('#formresponse_'+form_id).show(200);
				}
			}
		});
	});
	
	$('#msg p').each(function(){
		var el=$(this);
		$(this).prepend('<div class="msgclose">Close</div>');
		$(this).find('.msgclose').click(function(){
			el.slideUp(500);
		});
	});
	
	/* account.details */
	$('#formaccountdetails').submit(function(){
		if (!isValidEmailAddress($(this).find('input[name="v_email"]').val())) 
		{
			alert("Please enter a valid email address.");
			return false;
		}
	});
	
	$('.func-vcatpop').each(function(){
		var url="http://www.networkcatalogue.com/view/catalogues/"+$(this).attr('rel');
		if ($(this).hasClass('onload') && anch!='info') cp_vCatPopup(url);
		$(this).click(function(){cp_vCatPopup(url);return false;});
	});
	
	$('.link-back').click(function(){history.go(-1);});
	$('.link-switch').click(function(){$('#switchform').submit();});
	
	//shrinkLocation();

	$('.m-location ul li a.d').each(function(){
		if ($(this).attr('href')!='#' && $(this).attr('href')!=undefined && $(this).attr('href')!='')
		{
			var el=$(this);
			$.get($(this).attr('href')+'&inc=a',function(d){
				if (d=='') el.attr('title','').removeClass('d').html('&#9658;');
				else $(el).after(d);
				el.attr('href','#');
			});
			
		}
	});
	
	/* centralise list items where the list has a remainder */
	$('.m-category, .m-catlist-list ol').each(function(){
		var liw=$(this).find('li:first').width();
		var lis=$(this).children('li').length;
		var rem=lis % Math.floor($(this).width()/liw);
		if (rem>0) $(this).find('li:eq('+(lis-rem)+')').css('margin-left',liw/rem+'px');
	});
	
	$('.inputDate').datepicker({duration:0, dateFormat: 'd M yy'});

	testing();
	
});

/* custom fields */
;function cf_text(id) {
	alert(id);
	return 1;
}

;function addRemoveFav()
{
	
	$('.icon-fav-add, .icon-fav-remove').unbind().click(function(e){
		e.preventDefault();
		$(this).blur();
		el=$(this);
		elparentli=el.parents().filter('li');
		el.addClass('icon-loading');
		if (el.hasClass('icon-fav-add'))
		{
			var whatdo='add';
			var add='icon-fav-remove';
			var del='icon-fav-add';
		}
		else
		{
			var whatdo='del';
			var add='icon-fav-add';
			var del='icon-fav-remove';
		}
		$.get(el.attr('href')+'&inc=a&do='+whatdo,function(data){
			d=data.split('|');
			if (d[0]=='f') alert(d[1]);
			else el.removeClass('icon-loading').removeClass(del).addClass(add).attr('title','').html('<em>'+d[1]+'</em>');
		});
		if ($('#thispage').val()=='favourites') elparentli.animate({height:0,opacity:0},500).queue(function(){elparentli.remove();});
		else addRemoveFav();

	});
	
}

;function shrinkLocation(count)
{
	if (count==undefined) count=1;
	else if (count>5) return;
	$('.m-location').each(function(){
		var h=$(this).height();
		var lih=$(this).find('li').height();
		if (h>lih+10)
		{
			if (count==1)
			{
				$(this).prepend('<li class="m-location-showparents" title="Show parents"><a href="#">&#9668;</a></li>');
				$('.m-location-showparents').click(function(){$(this).parent().find('li').show();$(this).hide();});
			}
			/* need to go slightly longer way round */
			$(this).find('li:visible').addClass('v');
			$(this).find('li.v:not(".m-location-showparents"):first').removeClass('v').hide();
			shrinkLocation(count+1);
		}
	});
}

;function cp_vCatPopup(url)
{
	$('body').append('<iframe id="vcat" src="'+url+'" style="z-index:900; width:100%; height:100%; position:absolute; top:0; left:0;" frameborder="0"></iframe><div style="z-index:901; cursor:pointer; display:block; position:absolute; top:40px; right:0;" id="closevcat"><span style="border:1px solid #666; border-right:0; padding:5px 10px; background:#fff; ">Close catalogue viewer</span><span style="border:1px solid #666; border-right:0; padding:5px 10px; background:#c00; color:#fff; font-weight:bold;">X</span></div>');
	$('embed').hide(); /* need to hide flash */
	$('#outerwrapper').css({overflow:'hidden', height:$(window).height()-20+'px'});
	$('#closevcat').click(function(){
		$('#vcat, #closevcat').remove(); 
		$('#outerwrapper').css({overflow:'visible', height:'auto'});
		$('embed').show();
	});
	/*
	$.nyroModalManual({
		url:url
		, forceType:'iframe'
		, width:$(window).width()
		, minHeight:$(window).height()
		, autoSizable : false
	});
	*/
}


;function cp_logoFromWebsite(url)
{
	$.get('index.php?inc=a&go=misc&do=logofromweb&url='+url,function(d){
		$('#logofromwebtr td').html(d);
		$('#logofromwebtr').css('display','block');
	});	
}

;function testing()
{
	$('body').append('<div style="position:absolute; top:0; left:0; border:1px solid #999;"></div>');
}

;function isValidEmailAddress(emailAddress) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
}

;function cpInterruptNav(msg)
{
	if (msg=='enquiry') msg="You have unsaved changes to your enquiry sheet.";
	if (!msg) window.onbeforeunload = null; /* function(){return true;}; // turn off with cpInterruptNav(false); */
	else window.onbeforeunload =function(){return msg;};
}

;function cpActivateLinks()
{
	/* some of these rely on things being loaded via ajax, so they are in this function able to eb executed whenever */
	$('.link-login').click(function(e){
		e.preventDefault();
		$.nyroModalManual({
			url: 'index.php?inc=a&go=login'
			, endRemove: function(){cpLoadUserMenu();}
			, endShowContent: function(){cpBindLoginForm();}
		});
	});
}

;function cpBindLoginForm()
{
	$('.loginform').ajaxForm({ /* use a class because there are two */
		success: function(data,response,element) {
			d=data.split('|');
			if (d[0]=='f')
			{
				alert(d[1]);
			}
			else
			{
				/* IE can't clone password field so need to do this another way 
				$('.loginform').find('input[name="inc"]').remove();
				el=$('.loginform');
				element.clone(false).removeAttr("id").attr('id','loginpost').appendTo($("body"));
				$('#loginpost').submit();
				*/
				$('body').append('<form method="post" action="/" id="loginpost"><input type="hidden" name="go" value="login" /><input type="hidden" name="e" value="'+element.find('input[name="e"]').val()+'" /><input type="hidden" name="phash" value="'+d[1]+'" /></form>');
				$('#loginpost').submit();

			}
		}
	});
}

;function cpLoadUserMenu()
{
	$.get('index.php?inc=a&go=misc&do=usermenu',function(d){
		$('#box-usermenu').html(d);
		cpLoadEnquiryList();
		cpActivateLinks();
		cpBindLoginForm();
	});

	if ($('#logo-minilist').html()!='')
	{
		$.get('index.php?inc=a&go=misc&do=bondlogos',function(d){
			if (d!='') $('#logo-minilist').html(d);
		});
	}
}

;function cpLoadEnquiryList(d)
{
	if ($('#thispage').val()=='enquiry') return;

	$('#box-enquirylist').css({opacity:0.4});
	$('#box-enquirylist h3').text('Updating...');
	if (d==undefined)
	{
		if (true) 
		{
			
			$.get('index.php?inc=a&go=account.enquiry',function(d){
				$('#box-enquirylist').remove();
				if (d!=undefined && d!='')
				{
					$(d).insertAfter('#box-usermenu');
					if (false)
					{
						$('#box-enquirylist').hide();
						$('#box-enquirylist').slideDown(500);
					}
					$('.button-quickmode').click(function(){
						$.get('index.php?inc=a&go=account.enquiry&do=togglequickmode');
						$('.button-quickmode strong').toggle();
						$(this).blur();
						return false;
					});
					
					
					$('.m-miniprodlist li').each(function(){
						var li=$(this);
						$(this).find('.icon-enquiry-remove').click(function(e){
							e.preventDefault();
							var listcount=$('.m-miniprodlist li').length; /* how many at this time? */
							var url='index.php?inc=a&go=account.enquiry&do=remove&id=' + li.attr('id').split('-')[1];
							$.get(url);
							li.css('opacity',0.3);
							li.slideUp(300);
							
							if (listcount>5) cpLoadEnquiryList(); /* list is truncated to 5, plus a li with a link, so only refresh if it means loading a new item */
							else 
							{
								setTimeout(function(){
									li.remove();
									var listcount=$('.m-miniprodlist li').length;
									if (listcount==0) $('#box-enquirylist').slideUp(300);
								},300);
							}
						});
					});
				} /* if (d!=undefined && d!='') */
			});
		}
		else
		{
			setTimeout("cpLoadEnquiryList();",waitfor);
		}
	
	}
	else 
	{
		$('#box-enquirylist').remove();
		$(d).insertAfter('#box-usermenu');
	}

}

;function cpBindEnquiryQMQForm()
{
	$('#enquiry-form').ajaxForm({
		beforeSubmit: function(a,f,o) {
			$('#enquiry-form').css({opacity:0.4});
		}
		,success: function(d) {
			//console.log('cpBindEnquiryQMQForm success');
			$.nyroModalRemove();
			cpLoadUserMenu();
			d2=d.split('|');
			if (d2[1].substr(0,8)=='reloadvs') {
				console.log('reloadvs');
				if (typeof window.vs_refreshSelectors =='function')
				{
					vs_refreshSelectors();
				}
			}
		}
	});
}

;function cpLoginPop()
{
	
}

;function cpShowMe(el)
{
	el.show();
	var showmeMarginTop=parseInt(el.css("margin-top"));
	el.animate({marginTop:showmeMarginTop+20},100).animate({marginTop:showmeMarginTop},150).animate({marginTop:showmeMarginTop+8},200).animate({marginTop:showmeMarginTop},200).animate({marginTop:showmeMarginTop+3},200).animate({marginTop:showmeMarginTop},200);
}

$.fn.extend({
	cpprodpop: function(){
		$(this).hoverIntent(function(e){
			$('#cpprodpopped').remove();
			var src=$(this).find('img').attr('src');
			var winw=$(window).width();
			if (e.pageX > winw/2) left= (e.pageX - 340);
			else left=(e.pageX + 20);
			top=e.pageY-160;
			if (top<10) top=10;
			if (top>$(window).height()-160) top=$(window).height()-160;
			
			$('<div id="cpprodpopped" style="z-index:99; left:'+left+'px; top:'+top+'px;"><img id="cpprodpoppedimg" src="'+src+'" width="300" height="300" alt="Preview" /></div>').appendTo('body');
			
	
			var src=src.replace("125",300);
			var img = new Image();
			$(img).load(function(){
				$('#cpprodpoppedimg').attr('src',src);
			}).attr('src',src);
		}
		,function(){
			$('#cpprodpopped').remove();
		});
	}
	/*
	,fitmenu: function(){
		var n=$(this).find('li').length;
		var ulw=0;
		$(this).find('li a').each(function(){ulw+=1+$(this).width()+parseInt($(this).css('borderLeftWidth'))+parseInt($(this).css('borderRightWidth'))+parseInt($(this).css('paddingLeft'))+parseInt($(this).css('paddingRight'))});
		var addpadd=($(this).parent().width()-ulw)/(n);
		$(this).find('li a').each(function(){
			$(this).css({display:'block', minWidth:parseInt($(this).width())+addpadd+'px'});
		});
	}
	,fitmenu: function(){
		var css=$(this).css();
		var h=$(this).height();
		var w=$(this).width();
		var offset=$(this).offset();
		var table='<table class="'+$(this).className()+'" cellpadding="0" cellspacing="0" style="position:absolute; top:'+offset.top+'px; left:'+offset.left+'px; width:'+w+'px; height:'+h+'px;"><tr>';
		var style;
		var tdw=100/$(this).find('li').length;
		$(this).find('li').each(function(){
			table+='<td style="width:'+tdw+'%">'+$(this).html()+'</td>';
		});
		table+='</tr></table>';
		$('body').append(table);
		$('#fitmenu').css(css);
		$(this).hide();
	}
	*/
	
});

