/*
== CONTENTS ==============================

01 - Site Wide functions
02 - Image rollovers and thumbnail/carousel behaviours
03 - Product listing page
04 - Product comparison page
05 - FAQ Listing Show/Hide
06 - custom jQuery plugins

/*
== 01 ======================= SITE WIDE FUNCTIONS ============================*/

var Default = {

	// Equalise Height of a set of Items
	Equalise : function(elms) {
		var highest = 0, i;
		for (i=0; i < elms.length; i++){ if($(elms[i]).height() > highest) highest = $(elms[i]).height(); }
		for (i=0; i < elms.length; i++){ if($(elms[i]).height() < highest) $(elms[i]).height(highest); }

	},

	// Adds Class of 'last' to last Child of given Element
	LastListItem : function(el) {
		$(el).each(function() {
			$(this).children(':last').addClass('last');
		});
	},

	// Toggles Full Product List
	ProductListToggle : function() {
		var listContainer = $('div#product-list');
		$(listContainer).hide();
		var hasBeenClicked = false;

		$('#btn-az-toggle').click(function() {
			if (!hasBeenClicked)
				$('#list-toggle a:first').click(); // click the first tab
			else
				hasBeenClicked = true;

			if ($(this).hasClass('list-open')) {
				$(listContainer).hide();
				$(this).removeClass('list-open');
				$(this).addClass('list-close');
				$(this).text('Show the A-Z Product List');
			} else {
				$(listContainer).show();
				$(this).removeClass('list-close');
				$(this).addClass('list-open');
				$(this).text('Hide the A-Z Product List');
			}
			return false;
		});

		$('#btn-az-hide').click(function() {
			var toggleButton = $('#btn-az-toggle');
			$(listContainer).hide();
			toggleButton.removeClass('list-open');
			toggleButton.addClass('list-close');
			toggleButton.text('Show the A-Z Product List');
		});
	},

	//Designed for multi-line lists, where each line has a "last" list item
	ResizeUL: function(containerName, modNum) {
		var container = $(containerName);
		if (!container.length)
			return;

		var containerUL = container.children('ul');
		containerUL.each(function() {
			containerLi = $(this).children('li');
			containerLi.each(function() {
				if ((parseInt($(this).index())+1) % modNum == 0)
					$(this).addClass('last');
				else if ($(this).hasClass('last'))
					$(this).removeClass('last');
			});
		});
	},

	/*
	// Toggles My Product List
	MyProductsList : function() {
		if ($('#product-list-pod ul li').length > 5) {
			$('#product-list-pod ul').after('<a class="toggle closed" href="javascript:;"><span>Show all products in my list</span></a>');
			$('#product-list-pod ul').children('li:gt(4)').hide();
			var ogText = $('#product-list-pod a.toggle span').text();
			$('#product-list-pod a.toggle').toggle(function() {
				$('#product-list-pod ul').children('li:gt(4)').slideDown(200);
				$(this).children('span').text('Collapse my product list');
				$(this).removeClass('closed');
				$(this).addClass('open');
			},
			function() {
				$('#product-list-pod ul').children('li:gt(4)').slideUp(200);
				$(this).children('span').text(ogText);
				$(this).removeClass('open');
				$(this).addClass('closed');
			});
		}
	},
	*/

	// Accepts the <ul> element, how many items in each row (x), and whether their height should be equalised (bool)
	// Adds class of 'last' to last item in each row and 'clear' to the next item
	// List and list items still require styling in CSS for correct widths and margins
	HorizontalList : function(el,x,y) {
		$(el).each(function() {
			$(this).children('li:nth-child('+x+'n)').addClass('last');
			$(this).children('li:nth-child('+x+'n)').next('li').addClass('clear');
			if (y == true) {
				var items = $(this).children('li.item');
				var rows = Math.ceil(items.length / x);
				var rowStart;
				var rowEnd;
				var rowEq;
				var i = 0
				while (i < rows) {
					rowStart = i * x;
					rowEnd   = ((i + 1) * x);
					rowEq	= $(items).slice(rowStart, rowEnd);
					Default.Equalise(rowEq);
					if (i == rows-1) {
						$(rowEq).each(function() {
							$(this).addClass('bottom-row');
						});
					}
					i++;
				}
			}
		});
	},

	// Accepts the <ul> element, how many items in each row (x), and whether their height should be equalised (bool)
	// Adds class of 'last' to last item in each row and 'clear' to the next item
	// List and list items still require styling in CSS for correct widths and margins
	SimpleHorizontalList : function(el,x) {
		$(el).children('ul').each(function() {
			$(this).children('li:nth-child('+x+'n)').addClass('last');
			$(this).children('li:nth-child('+x+'n)').next('li').addClass('clear');
		});
	},

	/*
	// Only For General Landing Page - Displays Category Selector List in 3 Columns
	CategorySelector : function() {
		var items = $('div.category-selector ul li');

		//If only one <li> on the final line, insert an empty <li> before the penultimate <li>
		if (items.length%3 === 1) {
			$('<li/>').insertAfter( items.get(items.length-3) );
		}

		//Remove any whitespace after list items, as it is rendered between inline-block items
		items = $('div.category-selector ul');
		if (items.length) {
			items.html(items.html().replace(/<\/li>\s+/g, '</li>'));
		}
	},
	*/

	// Only For General Landing Page - Displays Category Selector List in 3 Columns sorted vertically
	CategorySelector: function () {
		var items = $('div.category-selector ul li');
		var columnLength = items.length / 3;
		columnLength = items.length == 4 ? [2, 1, 1] : [Math.ceil(columnLength), Math.ceil(columnLength), Math.ceil(columnLength) - (3-(items.length%3||3))];

		for (var i = 0; i < columnLength.length; i++) {
			$('div.category-selector ul > li:lt(' + columnLength[i] + ')').wrapAll('<div></div>');
		}
		$('div.category-selector ul > div:last').after('<br style="clear:both;" />');
	},

	Init : function() {
		Default.Equalise($('#top-nav li a'));
		Default.LastListItem($('ul.vertical'));
		Default.ProductListToggle();
		//Default.MyProductsList();
		Default.CategorySelector();
		Default.HorizontalList($('ul.party-listing'),3,0);
		Default.HorizontalList($('ul.horizontal-two'),2,1);
		Default.HorizontalList($('ul.horizontal-three'),3,1);
		Default.HorizontalList($('ul.horizontal-landing'),3,0);
		Default.HorizontalList($('div#category-subnav ul'),4,0);
		Default.HorizontalList($('div#rental-quote-pod div.promo ul'),2,0);
		Default.HorizontalList($('ul.vehicles'),4,0);
		Default.ResizeUL('.downloads-pod', 2);
		Default.SimpleHorizontalList($('ul.hori-three'),3);
		$('.vertical-general').find('.PagerControl').first().addClass('firstItem');

	}
}

/*
== 02 ======================= IMAGE ROLLOVERS AND THUMBNAIL/CAROUSEL BEHAVIOUR ============================*/

var ImageBehaviours = {

	ListImageHover : function(el,x) {
		$(el).each(function() {
			if (($(this).find('img')).length > 0) {
				if (($(this).find('h3 a, h2 a')).length > 0) {
					var heading = $(this).find('h3 a, h2 a');
				}
				var image = $(this).find('img:first');
				var imgWidth = $(image).outerWidth();
				var imgHeight = $(image).outerHeight();
				var parentLink = $(image).parent('a');
				$(parentLink).addClass('img');
				$(parentLink).width(imgWidth);
				$(parentLink).height(imgHeight);
				$(parentLink).prepend('<span></span>');
				var hoverSpan = $(parentLink).children('span');
				$(hoverSpan).width(imgWidth - (x ? 4 : 6));
				$(hoverSpan).height(imgHeight - (x ? 4 : 6));
				$(parentLink).hover(
					function() {
						$(hoverSpan).show();
						$(heading).addClass('hover');
					},
					function() {
						$(hoverSpan).hide();
						$(heading).removeClass('hover');
					}
				);
				$(heading).hover(
					function() {
						$(hoverSpan).show()
					},
					function() {
						$(hoverSpan).hide();
					}
				);
			}
		});
	},

	ThumbCarousel : function() {
		var carouselControls = '<a href="javascript:;" class="carouselPrev"></a><a href="javascript:;" class="carouselNext"></a>';
		$(".media-pod div.media-thumb-list").after(carouselControls);
		$(".media-pod .media-thumb-list").jCarouselLite({
			btnNext: ".media-pod a.carouselNext",
			btnPrev: ".media-pod a.carouselPrev",
			visible: 4,
			circular: false
		});
		$(".media-thumb-list a").click(function() {
			var imageURL = $(this).attr('href');
			$(".media-pod div.mid-image img").attr("src", imageURL);
			$(".media-pod a.image-enlarge, .media-pod a.functional-image-enlarge").attr("href", imageURL);
			return false;
		});
	},

	Init : function() {
		ImageBehaviours.ListImageHover($('ul.horizontal-landing li.item'),0);
		ImageBehaviours.ListImageHover($('ul.vertical-landing li.image-item'),1);
		ImageBehaviours.ListImageHover($('ul.vertical-general li.image-item'),0);
		ImageBehaviours.ListImageHover($('ul.horizontal-homepage li.item'),0);
		ImageBehaviours.ListImageHover($('ul.horizontal-three li.item'),0);
		ImageBehaviours.ListImageHover($('ul.horizontal-two li.item'),1);
		ImageBehaviours.ListImageHover($('div.media-thumb-list ul li'),1);
		ImageBehaviours.ListImageHover($('ul li.hoverImage'));
		ImageBehaviours.ListImageHover($('ul.party-listing li:has(h2 a)'));
		ImageBehaviours.ThumbCarousel();
	}
}

/*
== 03 ======================= PRODUCT LISTING PAGE ============================*/

var ProductListingPage = {

	CategorySubnav : function() {
		$('div#category-subnav h2').after('<a href="javascript:;" class="small toggle open">Hide Navigation</a>');
		var ogText = $('div#category-subnav a.toggle').text();
		$('div#category-subnav a.toggle').toggle(function() {
			$('div#category-subnav ul').slideUp(400);
			$(this).text('Show Navigation');
			$(this).removeClass('open');
			$(this).addClass('closed');
		}, function() {
			$('div#category-subnav ul').slideDown(400);
			$(this).text(ogText);
			$(this).removeClass('closed');
			$(this).addClass('open');
		});
	},

	CompareSubmit : function(btnID) {
		//$('#'+btnID).remove();
		$('ul.horizontal-two li.item input').next('label').after('<a style="display: none" class="submit" href="javascript:;">Compare Selected</a>');
	},

	CheckInputs : function() {
		var allCheckBoxes = $('ul.horizontal-two li.item input');
		var checkedBoxes  = $('ul.horizontal-two li.item input:checked');
		if (checkedBoxes.length == 0) {
			$(allCheckBoxes).next('label').next('a').hide();
			$(allCheckBoxes).next('label').show();
			$(allCheckBoxes).next('label').removeClass('single-check');
			$(allCheckBoxes).next('label').addClass('check');
			$(allCheckBoxes).next('label').text('Compare');
		}
		if (checkedBoxes.length == 1) {
			$(allCheckBoxes).next('label').next('a').hide();
			$(allCheckBoxes).next('label').show();
			$(allCheckBoxes).next('label').addClass('check');
			$(allCheckBoxes).next('label').text('Compare');
			$(checkedBoxes).next('label').text('Select another product');
			$(checkedBoxes).next('label').removeClass('check');
			$(checkedBoxes).next('label').addClass('single-check');
		}
		if (checkedBoxes.length > 1) {
			$(allCheckBoxes).next('label').next('a').hide();
			$(allCheckBoxes).next('label').show();
			$(allCheckBoxes).next('label').addClass('check');
			$(allCheckBoxes).next('label').text('Compare');
			$(checkedBoxes).next('label').removeClass('single-check');
			$(checkedBoxes).next('label').hide();
			$(checkedBoxes).next('label').next('a').show();
		}
	},

	ProductListComparing : function(btnID) {
		ProductListingPage.CheckInputs();
		/*$('ul.horizontal-two li.item span.check').click(function() {
			$(this).prev('input:checkbox').attr('checked',true);
			ProductListingPage.CheckInputs();
		});*/
		$('ul.horizontal-two li.item input:checkbox').click(ProductListingPage.CheckInputs);

		$('a.submit').click(function() {
			$('#'+btnID).click();
		});
	},

	Init : function(btnID) {
		ProductListingPage.CategorySubnav();
		ProductListingPage.CompareSubmit(btnID);
		ProductListingPage.ProductListComparing(btnID);
	}
}

/*
== 04 ======================= PRODUCT COMPARISON PAGE ============================*/

var CompTable = {

	RemoveColumn : function() {
		$('div.column').addClass('visible');
		var columns = $('#comparison-table-wrapper').children('div.visible');
		$(columns).last().addClass('column-last');
		$('div.column a.remove').click(function() {
			$(this).parents('div.column').removeClass('visible');
			$(this).parents('div.column').fadeOut(800, function() {
				$($('#comparison-table-wrapper').children('div.visible')).last().addClass('column-last');
				CompTable.WrapperWidth();
			});
		});
	},

	WrapperWidth : function() {
		var columns = $('#comparison-table-wrapper').children('div.visible');
		var newWidth = ((columns.length * 178) - 38);
		$('#comparison-table-wrapper').width(newWidth);
	},

	Init : function() {
		Default.Equalise($('#comparison-table-wrapper div.remove'));
		Default.Equalise($('#comparison-table-wrapper div.product'));
		Default.Equalise($('#comparison-table-wrapper div.price'));
		Default.Equalise($('#comparison-table-wrapper div.specs'));
		Default.Equalise($('#comparison-table-wrapper div.requirements'));
		var columns = $('#comparison-table-wrapper').children('div.visible');

		CompTable.RemoveColumn();
		CompTable.WrapperWidth();
	}
}

/*== 05 ======================= FAQ LISTING SHOW/HIDE ============================*/

var FaqListing = {

	Init : function() {

		var $faqs = $('div.faqs');
		$faqs.each(function() {
				$(this).children(':last').addClass('last-faq');
		});

		$('div.faq-group').each(function() {
			var parentDiv = $(this);
			var faqTitle = $(this).children('h2:first');
			var questionDiv = $(this).children('div:first');
			var faqToggle = '<a href="javascript:;" class="faq-toggle">show<span></span></a>';
			$(parentDiv).addClass('faq-closed');
			$(faqTitle).after(faqToggle);
			$(questionDiv).hide();
			$(faqTitle).hover(
				function() {
					$(this).css({'text-decoration':'underline','cursor':'pointer'});
					$(this).next('a.faq-toggle').addClass('toggle-hover');
				},
				function() {
					$(this).css({'text-decoration':'none'});
					$(this).next('a.faq-toggle').removeClass('toggle-hover');
				}
			);
			$(this).children('a.faq-toggle').hover(
				function() { $(this).prev('h2').css({'text-decoration':'underline'}); },
				function() { $(this).prev('h2').css({'text-decoration':'none'}); }
			);
			$(this).children('a.faq-toggle').click(function() {
				if ($(parentDiv).hasClass('faq-closed')) {
					$(parentDiv).removeClass('faq-closed');
					$(parentDiv).addClass('faq-open');
					$(this).text('hide');
					$(questionDiv).slideDown(400);
				}
				else if ($(parentDiv).hasClass('faq-open')) {
					$(questionDiv).slideUp(400, function() {
						$(parentDiv).removeClass('faq-open');
						$(parentDiv).addClass('faq-closed');
						$(this).parents('div.faq-group').find('a.faq-toggle').text('show');
					});
				}
			});
			$(faqTitle).click(function () {
				$(this).next('a.faq-toggle').click();
			});

		});

		$faqData = $.parseJSON( $faqs.attr('data-url') );

		var hashID = '';
		$.each($faqData, function (i, n) {
			$faqs.children('[data-division=' + n['division'] + ']')
				.attr('id', n['division'])
				.find('h2').click();
			hashID = n['division'];
		});
		document.location.hash = hashID;
	}
}

var SelectBoxReplace = {

	Init : function() {

		$('select.replace').each(function() {
			var el = $(this);
			var opts = $(el).children('option');
			var list;
				list = '<ul class="hidden">';
				for (i = 0; i < opts.length; i++) {
					list = list + '<li class="option-'+ i +'">' + $(opts.get(i)).html() + '</li>';
				}
				list = list + '</ul>';

			var ogText;
			if ($(el).children('option:selected')) {
				ogText = $(el).children('option:selected').text();
			} else {
				ogText = $(opts[0]).text;
			}
			var container = '<div class="search-opts" style="z-index:999;"><span>' + ogText + '</span>' + list + '</div>';
			$(el).after(container);
			$(el).hide();

			$('div.search-opts').click(function() {
				var list = $(this).children('ul');
				if ($(list).hasClass('hidden') == true) {
					$(list).show(1, function() {
						$(this).removeClass('hidden');
						$(this).addClass('open');
					});
				}
			});

			$(el).next('div.search-opts').find('ul li').click(function() {
				var optText = $(this).text();
				var parentList = $(this).parent('ul');
				$(parentList).parent('div').find('span').text(optText);
				var optNum = $(this).attr('class').replace('option-','');
				$(opts[optNum]).attr('selected','selected');
				var optVal = $(el).children('option:selected').val();
				$(el).val(optVal);
			});

			$(document).click(function() {
				$('div.search-opts ul.open').hide(1, function() {
					$(this).removeClass('open');
					$(this).addClass('hidden');
				});
			});
		});
	}
}

var CreateMap = {

	Init: function () {
		$('a#switch').click(function () {
			$('table.admin').toggle();
			$('div.map-branch-listing').toggle();
		});

		var lat = $('div.location-pod p.geocode span.latitude').text();
		var lng = $('div.location-pod p.geocode span.longitude').text();
		var zoom = 13;
		if (lat == '' || lng == '') { // Default to NZ
			lat = -41;
			lng = 172.5;
			zoom = 5;
		}
		var latlng = new google.maps.LatLng(lat, lng);
		var myOptions = {
			zoom: zoom,
			center: latlng,
			mapTypeControl: false,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);

		var markerIcon = '/Hirepool/images/ind/ind-map-marker.png';
		var marker = new google.maps.Marker({
			position: latlng,
			map: map,
			icon: markerIcon
		});

		google.maps.event.addListener(map, 'click', function () {
			location.href = $('#map-canvas').prev('a.more-link').attr('href');
		});
		google.maps.event.addListener(marker, 'click', function () {
			location.href = $('#map-canvas').prev('a.more-link').attr('href');
		});
	}
}

jQuery(document).ready(function($) {

	$('body').delegate('ul#list-toggle li a', 'click', function () {

		var $productListWrapper = $('#product-list-wrapper');
		var $waiting = $('.waiting', $productListWrapper);

		var $azProductList = $('#az-product-list');
		var $categoryProductList = $('#category-product-list');

		// get the # url of the link to find the target div by id
		var hash = this.hash;
		var target = $(hash);

		// cache bust every hour (approximate listing build cycle)
		var now = new Date();
		var cacheBust = now.getDate() + '-' + now.getMonth() + '-' + now.getFullYear() + '-' + now.getHours();

		//Sort data into columns
		var sortCols = function (data, list) {
			var totalLength = data.match(/<li/g);
			totalLength = (totalLength == null) ? 0 : totalLength.length;

			var subLength = 0;

			var numCols = 4;
			var headingSize = 4; //Size of a heading relative to size of a list item (which is size 1)

			var cols = [];
			for (var i = 0; i <= numCols; i++) { cols[i] = []; }

			data = data.split("</div><div class='dontsplit'>");
			totalLength += headingSize * data.length; //Account for section headings

			for (var i = 0; i < data.length; i++) {
				subLength += (/<li/g.test(data[i]) ? data[i].match(/<li/g).length : 0) + headingSize;

				//Use Math.ceil()-1 instead of Math.floor() to avoid final section from being placed outside the final column
				with ({index: Math.ceil(numCols*subLength/totalLength) - 1}) {
					cols[index][cols[index].length] = data[i];
				}
			}
			for (var i = cols.length-1; i >= 0; i--) { cols[i] = cols[i].join("</div><div class='dontsplit'>") }

			if (!list.hasClass('ready')) {
				list.addClass('ready');
				$waiting.hide();
			}

			return cols.join('</div></div><div class="product-list-column"><div class="dontsplit">') + '</div></div>';
		}

		// if the product list is not ready load ONCE via Ajax request
		if ( hash === '#az-product-list' ) {

			if (!$azProductList.hasClass('ready')) {
				$waiting.show();

				jQuery.get('/Hirepool/azprodlisting.html?cachebust=' + cacheBust, function (data) { $azProductList.html(sortCols(data, $azProductList)); }, 'text');
			}

			$('h1.category-product-list, p.category-product-list', $productListWrapper).hide();
			$('h1.az-product-list, p.az-product-list', $productListWrapper).show();
			$categoryProductList.hide();
			$azProductList.show();

		} else {

			if (!$categoryProductList.hasClass('ready')) {
				$waiting.show();

				jQuery.get('/Hirepool/azcatlisting.html?cachebust=' + cacheBust, function (data) { $categoryProductList.html(sortCols(data, $categoryProductList)); }, 'text');
			}

			$('h1.az-product-list, p.az-product-list', $productListWrapper).hide();
			$('h1.category-product-list, p.category-product-list', $productListWrapper).show();
			$azProductList.hide();
			$categoryProductList.show();

		}

		//$('#product-list-wrapper').prepend('<h1>'+ $(this.hash).children('h1').text() +'</h1><p>'+ $(this.hash).children('p').text() +'</p>');

		$('ul#list-toggle li a').removeClass('open');
		$(this).addClass('open');

		return false;
	});

	$('#rental-quote-pod').each(function () {
		$(this).find('select').selectorator();
	});

	$('fieldset.general').each(function () {
		$('select', this).selectorator();
		$('input[type=text]', this).each(function () {
			$(this).wrap('<div class="fake-input ' + $(this).attr('class') + '" />');
		});
		$('textarea', this).each(function () {
			$(this).wrap('<div class="fake-textarea ' + $(this).attr('class') + '" />');
		});
	});

	$('.print').click(function () {
		window.print();
		return false;
	});

	/*
	 * Slide-shows
	 * */
	$('#slideshow-container').each(function () {
		var slidesshow = $('#slideshow', this);
		var counter = $('#slideshow_counter', this);

		slidesshow.children().each(function (j) {
			counter.append('<div class="slideshow-progress" data-index="' + j + '" />');
		});

		var progress = $('.slideshow-progress', counter);

		slidesshow.hpslideshow({
			transitionCallback: function (index, $curr) {
				progress.removeClass('curr');
				progress.filter('[data-index=' + index + ']').addClass('curr');
			}
		});
		var prev = $('#slideshow_prev', this).click(function () {
			slidesshow.trigger('prev');
		});
		var next = $('#slideshow_next', this).click(function () {
			slidesshow.trigger('next');
		});
		progress.click(function () {
			slidesshow.trigger('jump', $(this).attr('data-index'));
		});
	});

	/*
	* Branch List
	* */
	$('.branch-list-data').each(function () {
		var branchList = $(this);

		var branchData = $.parseJSON(branchList.attr('data-data'));
		var showAll = $('#show-all-branches');
		var inputs = $('#branch-search-wrapper .row2 input');
		var search = $('#branch-search-wrapper form');
		var overlays = $('.mapOverlays li');
		var dataSearch = $.parseJSON($('div[data-search]').attr('data-search'));

		/* Set up Map */
		//alert('setup map');
		var map = $('#map-canvas').branchMap({
			showOverlay: function (obj) {
				if (overlays.filter('[data-branchid=' + obj['branchId'] + ']').is(':visible')) {
					overlays.hide();
				} else {
					overlays.hide();
					overlays.filter('[data-branchid=' + obj['branchId'] + ']').show();
				}
			}
		});

		overlays.delegate('.close', 'click', function () {
			overlays.hide();
		});

		/* Set markers */
		var latLngObj = {};
		$.each(branchData, function (i, n) {
			latLngObj[n['branchId']] = n;
		});
		map.trigger('addMarkers', latLngObj);

		/* Search map on form submit*/
//		search.submit(function () {
//			map.trigger('search', $('#branch-search-wrapper .row1 #location').val());
//			return false;
//		});

		/* Update the branch list */
		var updateBrances = function () {
			$('li', branchList).hide();

			/* Build an array of checked divisionid's
			* */
			var checked = [];
			inputs.each(function (i, n) {
				if ($(this).is(':checked')) {
					checked.push($(this).attr('data-branchid'));
				}
			});

			/* Show all the elements with checked divisionid's */
			$.each(checked, function (i, n) {
				$('[data-branchid=' + n + ']', branchList).show();
			});
		};

		inputs.change(function () {
			updateBrances();
			if ($(this).is(':checked') == true) {
				showAll.attr('checked', false);
			}
			showAll.attr('checked', false);
		});

		showAll.change(function () {
			if ($(this).is(':checked') == true) {
				$('#branch-search-wrapper div.row2 input').attr('checked', true);
			} else {
				$('#branch-search-wrapper div.row2 input').attr('checked', false);
			}
			updateBrances();
		});

		/*set the check-boxes*/
		$.each(dataSearch, function (i, n) {
		    map.trigger('search', n['address']);
		});
		search.submit();
		updateBrances();
	});

	var files = $('[type=file]').filestyle({
		image: "/hirepool/images/btn/btn-browse.png",
		imageheight : 30,
		imagewidth : 80,
		width : 250
	});

	$('#DivcvFile input.file').wrap('<div class="fake-input file" />').css({'width':'150px'});
});
