// code for navigation

$(document).ready(function() {
	/*hideLayer();*/
	$('.layer-close').live('click', function(e){
		e.preventDefault();
		$('#layer-bkg').fadeOut(500, function(){
			$('#layer').html('');
			$(this).hide();
		});
	});
	$('.layer-close-link').live('click', function(e){
		e.preventDefault();
		$('#layer-bkg').fadeOut(500, function(){
			$('#layer').html('');
			$(this).hide();
		});
	});



	$('.errorField').live('click', function(){
		$(this).removeClass('errorField');
		var id = $(this).attr('id');
		$('#'+id+'_error').html('');

	});
	
	/* GId
	/* toggle list item 
	var classFlag = new Date().getTime().toString();
	$('#ophthalmic-list li.orange div.hidden').slideDown().addClass(classFlag);
	$('li a').click(function(){
		if(!$(this).parents('li').children('div.hidden').hasClass(classFlag)){
			$('.'+classFlag).slideUp(300).removeClass(classFlag);
			$(this).parents('li').children('div.hidden').slideDown(600).addClass(classFlag);
		}
	});
	*/
	
	$('#ophthalmic-list dd a').click(function () {
			if ($(this).parent('h3').parent('dd').next('dt').css('display') == 'block')
			{
				$(this).parent('h3').parent('dd').next('dt').slideUp("slow");
			}
			else
			{
				$(this).parent('h3').parent('dd').parent('dl').children('dt').slideUp('slow');
				$(this).parent('h3').parent('dd').next('dt').slideDown("slow");
			}
	});

	/* check menu items */

	$('#menu a').click(function(event){
		
		var link = $(this).attr('href');
		switch(link){
			case 'loginregister.html':
				event.preventDefault();
				
				if ($(this).parent().attr('class') == 'ie6item')
				{
					document.location = 'http://www.moorfieldspharmaceuticals.co.uk/registerie6.html';
					return false;
				}
				else
				{
					showLayer('functionality/zf_register.html');
				}
				break;
			case 'my-account.html':
				event.preventDefault();
				showLayer('functionality/edit_account.html');
				break;
			case 'logout.html':
				event.preventDefault();
				accountLogout();
		}
		if($(this).parent('li').has('ul').length != 0) event.preventDefault();
		else return true;
	});

	/* team section */
	$('.team-image').click(function(){
		var rel = $(this).attr('rel');
		// hover oher images
		$('.team-image').removeClass('hover');

		$('.team-image').addClass('.team-image hover');

		$(this).removeClass('hover');

		$('.team-text').css('display', 'none');
		$('#team-'+rel+'-text').css('display', 'block');

		// show proper div
	});
	$('.team-text').css('display', 'none');

	/* Product section*/

	$('#search').click(function(e){
		e.preventDefault();
		if($(this).val() == searchLabel) $(this).val('');
	});
	$('#submit').click(function(e){
		if($('#search').val() == searchLabel) $('#search').val('');
		//if($('#search').val() == searchLabel){ $('#search').addClass('errorField'); e.preventDefault(); }
		//if($('#search').val() == ''){ $('#search').val(searchLabel); $('#search').addClass('errorField'); e.preventDefault(); }
		if($('#category').val() == 0 && $('#search').val() == ''){ 
			$('#category').addClass('errorField');
			$('#search').val(searchLabel).addClass('errorField');
//			$('#search').addClass('errorField');
			e.preventDefault();
		}
	});

	/* Certificates and Brochures */
	$(".pdf, .pdf_color").click(function(e){
		e.preventDefault();
		if($(this).hasClass('brochure')){
			return false;
		}else if($(this).hasClass('pdf-job')){
			var location = $(this).attr('href');
			window.open(location);
		}else{
			//$('.certificate').css('display', 'none');
			var id = $(this).attr('rel');
			var certDiv = $('#cert_'+id);
			$('.certificate').each(function(){
				if($(this).attr('id') != 'cert_'+id) $(this).hide(200);


			});
			var newX =e.pageX - 220;
			var newY = e.pageY - 50;
			certDiv.css('left', newX);
			certDiv.css('top', newY);
			certDiv.show(200);
		}
	});

	$(".view").click(function(e){
		e.preventDefault();
	});

	$('.close-cert').click(function(e){
		e.preventDefault();
		$('.certificate').hide(200);
	});

	$(".order").click(function(e){
		e.preventDefault();
		var id = $(this).attr('rel');
		var url = 'functionality/orderProduct.html?id='+id;
		showLayer(url);
	});

	$('.login_link').click(function(e){
		e.preventDefault();
		showLayer('functionality/zf_register.html');
	});

	/* Image library */
	$('.wtgallery_list a').click(function(e){
		var imgId = $(this).attr('href');
		var path = imgId.split(/\//);
		var fileName = path[(path.length - 1)];
		showLayer('functionality/image-request.html?id='+fileName);
		e.preventDefault();
	});

	/* Job list */
	$('.job-item').click(function(e){
		e.preventDefault();
		$('.description').slideUp(400);
		var id = $(this).attr('href');
		if($('.desc_'+id).css('display') == 'none'){
			$('.desc_'+id).slideDown(600);
		}
	});

	/* Images with rounded corners */
	  jQuery('.rounded-right').addClass('corners');
	  jQuery('.rounded-right').addClass('iradius12');
	  jQuery('.rounded-left').addClass('corners');
	  jQuery('.rounded-left').addClass('iradius12');

	  /* Registration number show div*/

	$('.regNum').live('click', function(event){
		event.preventDefault();
		var text ='Please enter your GMC NMC or Pharmacy registration number or equivalent.  We request this for security reasons to help prevent members of the public having access to areas of the website only intended to be viewed by healthcare professionals, which may otherwise contravene the advertising to the public legislation within the EU.';
		$('#regNumDiv').html('<a href="javascript: void(0);" class="close-regNumDiv"></a><h3>Registration Number</h3>'+text);
		var newX =event.pageX - 270;
		var newY = event.pageY - 50;
		$('#regNumDiv').css('padding', '10px');
		$('#regNumDiv').css('display', 'block');
		$('#regNumDiv').css('position', 'absolute');
		$('#regNumDiv').css('left', newX);
		$('#regNumDiv').css('top', newY);
		$('#regNumDiv').show(500);
	});

	$('.close-regNumDiv').live('click', function(event){
		$('#regNumDiv').hide(500);
	});

	$('.storCond').live('click', function(event){
		event.preventDefault();
		var text ='<ul><li>Normal Storage: Store below 25&deg;C</li><li>Refrigerate storage: Store between 2&deg;C and 8&deg;C</li><li>Freezer storage: Store below -18&deg;C or -20&deg;C</li></ul>';
		text += '<h3 style="text-decoration: underline;">Expiry once opened</h3><p>Preservative Free Eye Drops - 7 days in refrigerator<br />* Oil based Preservative Free Eye Drops - 28 days room temperature<br />';
		text += 'Eye Drops with preservatives - 28 days room temperature<br />Please check packaging for details</p>';

		$('#storCondDiv').html('<a href="javascript: void(0);" class="close-storCondDiv"></a><h3>Storage Conditions</h3>'+text);
		var newX =event.pageX - 270;
		var newY = event.pageY + 20;
		$('#storCondDiv').css('padding', '10px');
		$('#storCondDiv').css('display', 'block');
		$('#storCondDiv').css('position', 'absolute');
		$('#storCondDiv').css('left', newX);
		$('#storCondDiv').css('top', newY);
		$('#storCondDiv').show(500);
	});

	$('.COA').live('click', function(event){
		event.preventDefault();
		var text ='<p>Moorfields Pharmaceuticals can supply customers with Certificates of Analysis for all Category A Products.<br />'+
			'Please click on the PDF icons below to see if the product has any available to download. The number on the file name relates to the batch number.<br />'+
			'Contact our Customer Services Team if you are unable to download the certificate you require.</p>';

		$('#storCondDiv').html('<a href="javascript: void(0);" class="close-storCondDiv"></a><h3>Certificates of Analysis</h3>'+text);
		var newX =event.pageX - 270;
		var newY = event.pageY + 20;
		$('#storCondDiv').css('padding', '10px');
		$('#storCondDiv').css('display', 'block');
		$('#storCondDiv').css('position', 'absolute');
		$('#storCondDiv').css('left', newX);
		$('#storCondDiv').css('top', newY);
		$('#storCondDiv').show(500);
	});

	$('.close-storCondDiv').live('click', function(event){
		$('#storCondDiv').hide(500);
	});

	$('.showVideo').click(function(e){
		e.preventDefault();
		$('#layer-wait').show();
		$('#layer-bkg').fadeIn(500);
		$('#layer').load('fileadmin/templates/html/inner/video.html', function(){
			//center layer-window
			centerLayerWindow();
		});
		return false;
	});
});

function showLayer(url){
	if(url != null){
		//$('#layer-wait').html("<div class='spin-loader'><img src='fileadmin/templates/img/spin-loader.gif' alt='loading ...' /></div>");
		$('#layer-wait').show();
		$('#layer-bkg').fadeIn(500);
		$('#layer').load(url, function(){
			centerLayerWindow();
		});
	}
	return false;
}

function hideLayer(){
	$('#layer-bkg').fadeOut(500, function(){
		$('#layer').html('');
		$(this).hide();
	});
	return false;
}

function centerLayerWindow(){
	$('#layer-wait').fadeOut(500); $('#layer').fadeIn(500);

	var divWidth = $('.layer-window').width();
	var divHeight = $('.layer-window').height();
	//divWidth = divWidth.replace(/px/,'');
	//divHeight = divHeight.replace(/px/,'');

	var docWidth = $(window).width();
	var docHeight = $(window).height();


	var left = ((docWidth - divWidth) / 2)+'px';
	var top = ((docHeight - divHeight) / 2)+'px';
	//var top = '15%';
	//if(divHeight != 'auto')	top = ((docHeight - divHeight) / 2)+'px';
	$('.layer-window').css('left', left);
	$('.layer-window').css('top', top);

	//alert(docWidth+':'+docHeight);
	//alert(divWidth+':'+divHeight);
}


/* Login Register  [begin]*/

function zf_login(form_id){

	var pass = $('#pass').val();
	var user = $('#user').val();
	var permalogin = $('#permalogin').attr('checked');
	var challenge = $('#challenge').val();
	if(pass.length != 0){
		//save username and password if box checked
		if(permalogin){
			savePermalogin(user, pass);
		}
		//login
		var enc_pass = MD5(pass);
		var str = user+":"+enc_pass+":"+challenge;
		var encString = MD5(str);
		$('#pass').val( encString);


	}
	return zf_submitForm(form_id);
	
}

function zf_submitForm(id){
	var valid = validateForm(id);
	if(!valid) return false;
	var url = $('#'+id).attr('action');
	//check if url has get info
	var first_arg = url.match(/\?/);
	url += (first_arg == null)? '?redirect='+window.location.pathname : '&redirect='+window.location.pathname ;
	var dataString = '';
	$('#'+id+' :input').each(function(){
		var name = $(this).attr('name');
		var value = $(this).val();
		if(name.length != 0) dataString += name+'='+value+'&';
	});
	dataString = dataString.replace(/[&\s]+$/,"");
	$('#'+id+' .pinkButton span').html('submiting ...');
	$('#layer').fadeOut(200);
	$('#layer-wait').fadeIn(500);
	$.ajax({
		type: 'POST',
		url: url,
		data: dataString,
		success: function(data) {
			if (typeof(noFrame) == "undefined") 
			{
				$('#layer').html(data);
				centerLayerWindow();
				$('#layer-wait').fadeOut(500); 
				$('#layer').fadeIn(500);
			}
			else
			{
				document.location = 'http://www.moorfieldspharmaceuticals.co.uk/products/ophthalmic-specials/view-specials.html?all=1';
			}
	  }
	});

	return true;
}

function savePermalogin(user, pass){
	$.ajax({
		type: 'POST',
		url: 'functionality/zf_permalogin.html',
		data: 'username='+user+'&password='+pass,
		success: function(data) {
			//alert(data);
		}
	});
}

function validateForm(id){
	var error = false;
	$('#'+id+' :input').each(function(){
		var thisError = false;
		var message = '';
		var classes = $(this).attr('class');
		var id = $(this).attr('id');
		var value = $(this).val();
		//alert(id+':'+classes+':'+value);
		if(classes.match(/email/) && !isEmail(value)){
			error = true;
			thisError = true;
			message = 'Invalid email address.';
		}
		if(classes.match(/repeat/) && isRepeat(id, value)){
			error = true;
			thisError = true;
			message = 'Values do not match.';
		}
		if(classes.match(/unique/) && isUnique(id, value)){
			error = true;
			thisError = true;
			message ='Value not available, choose another.';
		}
		if(classes.match(/required/) && value.length == 0){
			error = true;
			thisError = true;
			message = 'This field is required.';
		}
		if(classes.match(/password/) && value.length < 6){
			error = true;
			thisError = true;
			message = 'The password must be at least 6 characters long.';
		}
		if(thisError){
			$('#'+id).addClass('errorField');
			$('#'+id+'_error').html(message);
			if($('#'+id).attr('id') == null){
				alert(message);
			}
		}else{
			$('#'+id+'_error').html('');
		}
	});
	return(!error);
}

function applyJob(id){
	var url = 'functionality/apply-job.html?id='+id;
	showLayer(url);
}


function forgetPass(){
	$('#forgotten_password').toggle();
}

function accountLogout(){
	$.ajax({
		type: 'POST',
		url: 'functionality/zf_register.html',
		data: 'logintype=logout&pid=34',
		success: function(data) {
			//window.location.reload(true);
			window.location = '/home.html';
	  }
	});
}

function backToLogin(){
	showLayer('functionality/zf_register.html');
}

/* Login Register [end] */

Array.prototype.contains = function (element) {
	for (var i = 0; i < this.length; i++) {
		if (this[i] == element) {
			return true;
		}
	}
	return false;
}
function isEmail(email){
	var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
	return (filter.test(email));
}

function isRepeat(id, value){
	var otherId = id.replace(/_repeat/,"");
	var otherVal = $('#'+otherId).val();
	return (value != otherVal);
}

function isUnique(id, value){
	return false;
	value = hex_md5(value);
	var unique = true;
	for(i=0; i< enc_data['email']; i++){
		if(enc_data['email'][i] == value){ unique = false; alert(value);}
	}
	return !unique;
}

function changeNewsletter(){
	var checked = ($('#newsletter-checker').val() !== null)? 1 : 0;
	$('#newsletter').val(checked);
}



