// JavaScript Document

// EDIT THESE VALUES IF REQUIRED
var alertText = 'Are you sure you wish to perform this action' + "\n"; //DEFAULT TEXT DISPLAYED ON CONFIRM BUTTONS/LINKS WHEN NO ALT/TITLE
var newWindowLink = true; //OPEN EXTERNAL LINKS BY DEFAULT IN A NEW WINDOW (TRUE/FALSE)?

var woms = new Array(); //CREATE ARRAY OF FUNCTIONS TO LAUNCH ONLOAD

//Show the loading image
function show_progressbar(element) {
	
	element.html('<img src="images/loading.gif" alt="Loading" style="margin-top: 10em;" />');

}

//Manages the panels that drop down from the pet menu
function petPanels() {

	$('.expand_panel').click(function() { //Find links that expand the page panel and wait for a click
									  
		var panel = $('.content_window'); //Get the panel on the page which needs to expand
		
		show_progressbar(panel);
		
		var page_to_load = $(this).attr('href'); //Get the href of the link that was clicked
		
		var url = page_to_load.split('.');
		
		panel.attr('id', url[0]);
		
		$('.expand_panel').removeClass('active'); //Remove all active classes from the other links in the menu
		
		$(this).addClass('active'); //Add a class to the active link
		
		if(panel.is(':hidden')) { //See if the panel is already hidden
		
			panel.slideDown(1500);
			
			if($('#home_content').length > 0) {
			
				applyMargin('home_content', 47.5, 16);
			
			} else {
				
				applyMargin('content', 47.5, 16);
				
			}


		} else { //The panel is already displayed
		
			//panel.slideUp(); //Hide it
		
		}
		
		//panel.load('pages/page_handler.php?url=' + url[0]); //Load in the requested page
		panel.load('libs/includes/pet_drop_down.php?pet=' + url[0]); //Load in the requested page
		
		return false; //Stop the user from 
	
	});

}

//When we open up the pet panel we need to move the page conten as well
function applyMargin(element_id, extra_margin, current_margin) {

	$('#'+element_id).animate({ //Get the element to animate
		marginTop: (extra_margin+current_margin)+'em' //Increment the margin top
	}, 1500 );

}

//Closes the pet panel
function closePetPanel() {

	$('.hide_pet_panel').click(function() { //Listen for a click on the hide button
		
		var panel = $('#content_window'); //Get the panel details
		
		panel.slideUp(); //Close the panel
		
		return false;
	
	});

}

function h1Replace() {

	if($('h1').length == 0) return false; //Check headings exist

	var headings = $('h1');
	
	//Loop through headings
	$(headings).each(function () {
							   
		var parentClass = $(this).parent().attr('class'); //Get the class of the parent element	
		
		if($(this).attr('class') == 'home') { //Find the class for this heading
		
			if(typeof sIFR == "function"){
				
				sIFR.replaceElement("h1", named({sFlashSrc: "flash/brighton_medium.swf", sColor: "#5a0048", sWmode: "transparent"}));
			};
		
		} else { //The heading isn't on the HP and needs to have SIFR replace	
			
			if(parentClass == '') { //The heading isn't in a container
	
				if(typeof sIFR == "function"){
					sIFR.replaceElement("h1", named({sFlashSrc: "flash/VAGRoundedBT.swf", sColor: "#b5111b", sWmode: "transparent"}));
				};
			
			} else { //The heading is in the content section of the site
				
				if(typeof sIFR == "function"){
					sIFR.replaceElement("h1", named({sFlashSrc: "flash/VAGRoundedLT.swf", sColor: "#404c12", sWmode: "transparent"}));
				};
				
			}
	
		}
	
   });

}

function h2Replace() {
	
	if($('h2').length == 0) return false; //Check headings exist
	
	var headings_2 = $('h2');
	
	$(headings_2).each(function () {
	
		var parentClass = $(this).parent().attr('class')
	
		if(typeof sIFR == "function"){
			
			var color = '#56004E';
			
			if(parentClass.indexOf('supadog') > -1) {
			
				color = '#303285';
			
			} else if(parentClass.indexOf('supacat') > -1) {
			
				color = '#7E0001';
			
			} else if(parentClass.indexOf('supahamster') > -1) {
			
				color = '#5A0048';
			
			} else if(parentClass.indexOf('suparat') > -1) {
				
				color = '#E62C31';
				
			} else if(parentClass.indexOf('suparat') > -1) {
				
				color = '#F29B4B';
				
			} else if((parentClass.indexOf('rabbit') > -1) || (parentClass.indexOf('chinchilla') > -1) ||(parentClass.indexOf('guinea-pig') > -1)) {
			
				color = '#404c12';
			
			}
			
			sIFR.replaceElement("h2", named({sFlashSrc: "flash/VAGRoundedLT.swf", sColor: color, sWmode: "transparent"}));
			
		};
	
	});
	
}

//Highlights values of inputs on focus
function highlightValues() {
	
	if($('input').length == 0) return false; //Check that there are inputs on the page
	
	$('input').each(function() { //Loop through each input on the page
	
		$(this).focus(function() { //Listen for the input getting focus
		
			$(this).select();
		
		});
	
	});
	
	
}

function productInfo() {

	if($('.more_info').length == 0) return false;
	
	$('.more_info div').css('display', 'none'); //Hide the div
	
	$('.more_info a').click(function() { //Find the clicked element
		
		var div = $(this).parent().next(); //Get the div we need to expand
		
		$('.more_info div').slideUp('slow'); //Slide up all the open divs
		
		if(div.is(':hidden')) { //Is the div hidden
		
			div.slideDown('slow'); //Expand the div
		
		}
		
		return false;
	
	});

}

//Sets the product grids to be the same height
function productGrid() {

	if($('.shop_product').length == 0) return false;
		
	var productCells = $('.shop_product');
	var maxHeight = 0;
	
	for(var i=0; i<productCells.length; i++) {
	
		var cellHeight = productCells[i].offsetHeight;
	
		if(cellHeight > maxHeight) {
		
			maxHeight = cellHeight;
		
		}
	
	}
	
	for(var i=0; i<productCells.length; i++) {
	
		$(productCells[i]).css('height', maxHeight + 'px');
	
	}

}

//Sets the values of the delivery address
function deliveryAddress() {
	
	if($('#use_billing').length == 0) return false;
	
	$('#use_billing').click(function() {
	
		if($(this).is(':checked')) {
			
			$('#delivery_title').val($('#title').attr('value'));
			$('#delivery_first_name').val($('#first_name').attr('value'));
			$('#delivery_last_name').val($('#last_name').val());
			$('#delivery_telephone_number').val($('#telephone_number').val());
			$('#delivery_email_address').val($('#email_address').val());
			$('#delivery_house_number').val($('#house_number').val());
			$('#delivery_address_1').val($('#address_1').val());
			$('#delivery_address_2').val($('#address_2').val());
			$('#delivery_address_3').val($('#address_3').val());
			$('#delivery_town').val($('#town').val());
			$('#delivery_county').val($('#county').val());
			$('#delivery_postcode').val($('#postcode').val());
			$('#delivery_country').val($('#country').val());
		
		} else {
			
			$('#delivery_title').val('');
			$('#delivery_first_name').val('');
			$('#delivery_last_name').val('');
			$('#delivery_telephone_number').val('');
			$('#delivery_email_address').val('');
			$('#delivery_house_number').val('');
			$('#delivery_address_1').val('');
			$('#delivery_address_2').val('');
			$('#delivery_address_3').val('');
			$('#delivery_town').val('');
			$('#delivery_county').val('');
			$('#delivery_postcode').val('');
			$('#delivery_country').val('0');
			
		}
	
	});
	
}

function showDeleteButton(value, id) {

	for(var i=2; i<=value; i++) {

		var button = document.getElementById('delete_'+id+'_'+i);
		button.className = 'delete';
		
	}
	
}

function copyElement() {
	
	if(!document.getElementById('add_1')) return false;

	var images = document.getElementsByTagName('img'); //GET IMAGES ON PAGE
	
	var copiable = document.getElementsByTagName('*');
	
	for(var x=0; x<copiable.length; x++) {
	
		if(copiable[x].className.indexOf('copiable') > -1) {
	
			var id = copiable[x].getAttribute('id');
	
			var currentOptions = document.getElementById(id + '_options');
			
			if(currentOptions.value > 1) showDeleteButton(currentOptions.value, id); //SHOW DELETE OPTION IF ONLY ONE ON PAGE
			
			for(var i=0; i<images.length; i++) { //LOOP
			
				if(images[i].className == 'add') { //ADD BUTTON
				
					images[i].onclick = function () { //CLICKED
					
						var optionId = this.parentNode.parentNode.getAttribute('id');
					
						elementOptions = document.getElementById(optionId + '_options');
					
						cloneElement(this, elementOptions);
					
					}
					
				}
				
				if(images[i].className == 'delete') { //DELETE BUTTON
				
					images[i].onclick = function () { //CLICKED
					
						var optionId = this.parentNode.parentNode.getAttribute('id');
					
						elementOptions = document.getElementById(optionId + '_options');
					
						removeElement(this, elementOptions);
					
					}
				
				}
			
			}
		
		}
	
	}
	
}

function removeElement(clickedButton, currentNum) {

	var elementsOnPage = parseInt(currentNum.value); //FINDS NUMBER OF LISTS ON PAGE
	var newValue = elementsOnPage-1; //DECREASES BY 1

	var listElement = clickedButton.parentNode; //LI ELEMENT BUTTON SITS IN
	var toRemove = listElement.parentNode; //UL ELEMENT TO REMOVE
	var topLi = toRemove.parentNode; //PARENT OF toRemove
	
	var removeElement = topLi.removeChild(toRemove); //REMOVE ELEMENT
	
	removeElement; //REMOVE ELEMENT
	
	reSetIds(topLi, newValue); //ID VALUES NEED TO BE RESET IF A LIST IS REMOVED
	
	updateElementsNumber(currentNum, newValue); //UPDATE NUMBER OF LIST ON PAGE
	
	copyElement();

}

function reSetIds(parentElement, newValue) {

	var uls = parentElement.getElementsByTagName('ul');
	var elements = parseInt(newValue);
	var count = 1;
	
	for(var i=0; i<uls.length;i++) {
			
		updateFieldAttributes(uls[i], count, false);
		
		count++;
	
	}

}

function cloneElement(clickedButton, currentNum) {
	
	var elementsOnPage = parseInt(currentNum.value); //FINDS NUMBER OF LISTS ON PAGE
	var newValue = elementsOnPage+1; //INCREASES BY 1
	
	var listElement = clickedButton.parentNode; //LI ELEMENT THAT BUTTON SITS IN
	var toClone = listElement.parentNode; //UL ELEMENT TO CLONE
	var appendTo = toClone.parentNode; //ADD IT TO THE LI
	
	var new_element = toClone.cloneNode(true); //CREATE CLONE
	var applyElement = appendTo.appendChild(new_element); //ADD TO PAGE
	
	applyElement; //ADD
	
	updateFieldAttributes(new_element, newValue, true);
	
	updateElementsNumber(currentNum, newValue); //UPDATE NUMBER OF LIST ON PAGE
	
	copyElement(); //RELODE DOM
	
}

function setAttributes(obj, newIdValue, clearValue) {

	for(var i=0; i<obj.length; i++) {
		
		var attributes = obj[i].attributes
		
		for(var y=0; y<attributes.length; y++) {
		
			if(attributes[y].name.indexOf('jQuery') > -1) {
		
				obj[i].setAttribute(attributes[y].name, '100000' + Number(attributes[y].value)+1);
			
			}
		
		}
		
		
	
		//SET VARS
		var existingId   = '';
		var existingName = '';
		var existingFor  = '';
		var attrName     = 'for'; //IE NEED A DIFFENT ATTR FOR 'for'
		var newId        = '';
		var newName      = '';
		var newFor       = '';
		
		//GET EXISTING ID AND NAME ATTRS
		existingId   = obj[i].getAttribute('id');
		existingName = obj[i].getAttribute('name');
		
		//GET FOR ATTR
		if(navigator.appName=="Microsoft Internet Explorer") { //CHECK BROWSER
			
			existingFor =obj[i].getAttribute('htmlFor');
			attrName    = 'htmlFor';
			
		}else{
			
			existingFor=obj[i].getAttribute('for');
			
		}		
		
		//UPDATE ID VALUE
		if(existingId != null && existingId != '') { //CHECK IF ID ATTR EXISTS
		
			var Idmakeup = existingId.split('_'); //SPLIT EXISTING ID ON _
			for(var x=0; x<Idmakeup.length; x++) {
			
				if(x < (Idmakeup.length-1)) {
			
					newId += Idmakeup[x]+'_';
				
				}
			
			}
			
			newId = newId.substr(0, (newId.length-1));
			
			newId        += '_'+newIdValue; //BUILD NEW ID
			obj[i].setAttribute('id', newId); //APPEND NEW ATTR
		
		}
		
		//UPDATE NAME VALUE
		if(existingName != null) { //CHECK IF NAME ATTR EXISTS
		
			var Namemakeup = existingName.split('_'); //SPLIT EXISTING NAME ON _
			for(var x=0; x<Namemakeup.length; x++) {
			
				if(x < (Namemakeup.length-1)) {
			
					newName += Namemakeup[x]+'_';
				
				}
			
			}
			
			newName = newName.substr(0, (newName.length-1));
			
			newName        += '_'+newIdValue; //BUILD NEW NAME
			obj[i].setAttribute('name', newName); //APPEND NEW ATTR
		
		}
		
		//UPDATE FOR VALUE
		if(existingFor != null) { //CHECK IF FOR ATTR EXISTS
			
			var Formakeup = existingFor.split('_'); //SPLIT EXISTING NAME ON _
			for(var x=0; x<Formakeup.length; x++) {
			
				if(x < (Formakeup.length-1)) {
			
					newFor += Formakeup[x]+'_';
				
				}
			
			}
			
			newFor = newFor.substr(0, (newFor.length-1));
			
			newFor        += '_'+newIdValue; //BUILD NEW FOR
			obj[i].setAttribute(attrName, newFor); // APPEND NEW FOR
			
		}
		
		if(clearValue == true) {
			
			var class_name = obj[i].className;
			
			if(class_name.indexOf('select_list') > -1) {
				
				obj[i].value = '0'; //SET NEW VALUE TO BLANK
				
			} else {
			
				obj[i].value = ''; //SET NEW VALUE TO BLANK
			
			}
		
		}
	
	}

}

function updateFieldAttributes(parentElement, newId, resetValue) {
	
	//ARRAY OF ELEMENTS
	var inputs = parentElement.getElementsByTagName('input');
	var selects = parentElement.getElementsByTagName('select');
	var textarea = parentElement.getElementsByTagName('textarea');
	var images = parentElement.getElementsByTagName('img');
	var labels = parentElement.getElementsByTagName('label');
	
	//SET NEW ATTRS
	setAttributes(inputs, newId, resetValue);
	setAttributes(selects, newId, resetValue);
	setAttributes(textarea, newId, resetValue);
	setAttributes(images, newId, resetValue);
	setAttributes(labels, newId, false);
	
	
}

var element_id = '';

function petBreeds() {
	
	if($('#animal').length == 0) return false;
	
	var pets = $('.update_breed').change(function() {
		
		element_id = $(this).attr('id');
		
		$.ajax({
			type: "GET",
			url: "libs/includes/pet_breeds.php?pet_id=" + $(this).val(),
			success: function(html) {
				$('#breed').html(html);
			}
		});
	
	});

}

function updateElementsNumber(field, number) {

	field.value = number;

}

function dropMenu() {

	if(!document.getElementById('top_nav')) return false;
	
	var top_nav = document.getElementById('top_nav');
	var lis = top_nav.getElementsByTagName('li');
	var drop = new Array;
	
	for(var i=0; i<lis.length; i++) {
	
		var submenu = lis[i].getElementsByTagName('ul');
	
		if(submenu.length > 0) {
	
			lis[i].onmouseover = function() {
	
				var submenu = this.getElementsByTagName('ul');
				
				submenu[0].className = 'over';
	
				//drop[i]= lis[i].getElementsByTagName('ul');
			
			}
			
			lis[i].onmouseout = function() {
			
				var submenu = this.getElementsByTagName('ul');
				submenu[0].className = '';
			
			}
		
		}
	
	}

}

//ONLOAD MANAGER
function womOn(){
  window.onload = womGo;
}

function womGo(){
  for(var i = 0;i < woms.length;i++)
    eval(woms[i]);
}

function womAdd(func){
  woms[woms.length] = func;
}

//Manage the google map for pet advisor
function siteLocation() {
	
	if($('#centre_profile').length == 0) return false;
	
	centreLocation();
	
}

//
function allowPostcodeSearch() {
	
	if($('#find_postcode').length == 0) return false;
	
	$('#find_postcode').removeClass('hidden');
	
	postcodeSearch($('#find_postcode'));
	
}

function applySearch() {

	if($('#advisor_search_form').length == 0) return false;
	startSearch();

}

function searchResults() {

	if($('.toggle_result').length == 0) return false;
	toggleResult();

}

//Hides the results for the advisor, so people with JS get full effect
function hideAdvisorPanels() {

	if($('.toggle_result').length == 0) return false;
	
	$('.advisorDetails').addClass('hidden');
	
	return false;

}

function advisorReview() {

	if($('.review').length == 0) return false;
	
	$('.review').click(function() {
	
		//Get the ids of the element
		var centre_el = $(this).parent().parent().attr('id');
		var review_el = $(this).attr('id');
		
		//Split the ids
		var centre_bits = centre_el.split('_');
		var review_bits = review_el.split('_');
		
		//Get the numeric id
		var centre_id = centre_bits[1];
		var review_id = review_bits[1];
		
		var score = $(this).html();
		
		$.ajax({
			type: "GET",
			url: "libs/includes/ajax/rate_centre.php?centre_id=" + centre_id + "&review_id=" + review_id + "&score=" + score,
			success: function(html) {
				$('#result_' + centre_id).html(html);
			}
		});
		
		$.ajax({
			type: "GET",
			url: "libs/includes/centre_stars.php?centre_id=" + centre_id,
			success: function(html) {
				$('#centre_' + centre_id).html(html);
			}
		});
		
		return false;
	
	});

}

//Toggles the registration form between rescue centres and other businesses
function advisorRegister() {

	if($('#rescue_locator').length == 0) return false;
	
	var business_type = $('#business_type');
	
	business_type.change(function() {
	
		var website = $('#mini_website');
		website.addClass('hidden');
		
		if($(this).val() == 'Rescue Centres') {
			
			website.removeClass('hidden');
			
		}
	
	});
	

}

//Toggles the search for re-homing pets on the gallery
function gallerySearch() {
	
	if($('#refine_gallery_search').length == 0) return false;
	
	$('#refine_gallery_search').click(function() { //Click on the link
	
		var form = $('#search_criteria');
		
		if(form.is(':hidden')) {
		
			form.slideDown();
			$(this).html('Hide');
			$(this).addClass('hide');
		
		} else {
			
			form.slideUp();
			$(this).html('Search');
			$(this).removeClass('hide');
			
		}
	
		return false;
	
	});
	
}

//Checks the advisor search function for the type of search required
function advisorSearch() {

	if($('#advisor_search_form').length == 0) return false; //Does the form appear on the page
	
	var category = $('#category'); //Get the category drop down
	
	checkType(category.val()); //Check the value of the category
	
	category.change(function() {
	
		checkType($(this).val());
	
	}); //The category drop down has changed
	

}

//Mange the category types to display the correct fields
function checkType(selectedCategory) {
	
	var brandContainer   = $('#brand_id').parent(); //Get the brand list container
	var animalType       = $('#type_of_animal').parent(); //Get the animal list container
	
	if(selectedCategory == 'Pet Shops' && brandContainer.is(':hidden')) { //The value is pet shops and is the element hidden
		
		brandContainer.slideDown('slow'); //Show the container element
		
	} else if(selectedCategory != 'Pet Shops') { //Is the selected category not a pet shop
	
		brandContainer.slideUp(); //Hide the element
	
	}
	
	if(selectedCategory == 'Rescue Centres' && animalType.is(':hidden')) {
	
		animalType.slideDown('slow');
	
	} else if(selectedCategory != 'Rescue Centres') {
	
		animalType.slideUp();
	
	}
	
}

function centreRegistration() {

	if($('#business_type').length == 0) return false;
	
	checkBusinessType($('#business_type').val());
	
	$('#business_type').change(function() {

		checkBusinessType($(this).val());

	});
	
}

function checkBusinessType(type) {

	if(type == 'Dog walking beaches/parks etc') {
			
		$('#left form li[class!=beach]').addClass('hidden');
		$('#centre_name').parent().children('label').html('Beach / Park Name');
		
	} else if(type == 'Pet Shops') {
		
		$('#charity_item').addClass('hidden');
		
	} else {
		
		$('#left form li[class!=beach]').removeClass('hidden');
		$('#centre_name').parent().children('label').html('Business Name');
		
	}

}

function alltheabove() {

	if($('.all_above').length == 0) return false;
	
	var inputs = $('input[type="checkbox"]');
	
	$(inputs).click(function() {
	
		if($('.all_above').is(':checked')) {
		
			var all_id = $(this).attr('id');
			
			inputs.each(function() {
								 
				if($(this).attr('type') == 'checkbox' && $(this).attr('id') != all_id) {
				
					$(this).attr('checked', '');
				
				}
			
			});
		
		}
	
	});

}

//Toggles the display of the BRC membership number required for the BRC promotional code
function BRCPromo() {
	
	if($('#offer_code').length == 0) return false; //Check that we're on the correct page

	var membership = $('#brc_code').parent();

	if($('#offer_code').val().toLowerCase() != 'brc09') {

		membership.toggle();
	
	}
	
	$('#offer_code').keyup(function() { //Has the key been pressed
	
		var code = $(this).val(); //Get the code entered in to the field
	
		code = $.trim(code); //Remove the white space from the code
	
		if(code.toLowerCase() == 'brc09') { //Set the code to be lower case and match it against the BRC09 promo
		
			if(membership.is(':hidden')) {
		
				membership.toggle();
			
			}
		
		} else {
		
			if(membership.is(':visible')) {
				
				membership.toggle();
				
			}
		
		}
	
	});
	
	
}

//JQUERY MANAGER
$(document).ready(function() {
						   
   // do stuff when DOM is ready
   petPanels();
   closePetPanel();
   highlightValues();
   h1Replace();
   h2Replace();
   productInfo();
   productGrid();
   deliveryAddress();
   memberPets();
   allowPostcodeSearch();
   siteLocation();
   applySearch();
   searchResults();
   hideAdvisorPanels();
   advisorReview();
   advisorRegister();
   petBreeds();
   gallerySearch();
   advisorSearch();
   centreRegistration();
   
   alltheabove();
   
   BRCPromo();
   
});

function CreateBookmarkLink() {

	title = document.title;
	url = window.location.href;
	
	if (window.sidebar) { 
		window.sidebar.addPanel(title, url,"");
	} else if(window.external) {
		window.external.AddFavorite( url, title); 
	} else if(window.opera && window.print) {
		return true;
	}
	
}

function objToggle(obj) { 

	var obj = document.getElementById(obj);

	if(obj.style.display == "block") { 
		obj.style.display = "none";
	} else { 
		obj.style.display = "block";
	}

}

function memberPets() {
	
	if(!document.getElementById('pet_1')) return false;
	
	var counter = document.getElementById('pet_options');
	var toshow = document.getElementById('maxPets');
	
	for(var i=0; i<toshow.value; i++) {
	
		if(i>=counter.value) {
	
			document.getElementById('pet_' + (i+1)).className = 'hidden';
		
		}
	
	}
	

}

function addPet() {

	var counter = document.getElementById('pet_options');
	
	var newCount = Number(counter.value)+1;
	
	if(newCount < 7) {
	
		var pet = document.getElementById('pet_' + newCount);
		pet.className = "";
		
		counter.value = newCount;
	
	} else {
	
		alert('You are unable to add any further pets');
	
	}

}

function removePet() {

	var counter = document.getElementById('pet_options');
	
	var newCount = Number(counter.value)-1;
	
	if(newCount >= 1) {
	
		var pet = document.getElementById('pet_' + newCount);
		pet.className = "hidden";
		
		counter.value = newCount;
	
	} else {
	
		alert('You are unable to delete this pet');
	
	}

}

//Preload loading image
var progress_bar = new Image();
progress_bar.src = '../images/loading.gif';