window.addEvent('domready', function() {
	
	var tab = querySt('tab');
	

	
	
	if(typeof(tab) !== 'undefined' && tab != null) {
		
		
		
		window.location.hash = tab;
		
	}
	

	new SmoothScroll({  duration:700  }, window);
		
});

function facebook_login(){
	
	window.location.href = '/login/q/action-facebook/';
}


function facebook_logout(){
	
	FB.logout(function(response) {
		  // user is now logged out
		window.location.href = '/users/logout';
	});
	return false;
}

function querySt(ji) {
	hu = window.location.search.substring(1);
	gy = hu.split("&");
	for (i=0;i<gy.length;i++) {
	ft = gy[i].split("=");
	if (ft[0] == ji) {
	return ft[1];
	}
	}
	}


if(this.name == 'printform' && window.print){
	window.print();
}


if(!Array.indexOf){
  Array.prototype.indexOf = function(obj){
   for(var i=0; i<this.length; i++){
    if(this[i]==obj){
     return i;
    }
   }
   return -1;
  }
}

function clrForm(formEl,initVal){
	if(formEl.value == initVal){
		formEl.value = '';
	}
}

function urldecode(str) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // %          note: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // *     example 1: urldecode('Kevin+van+Zonneveld%21');
    // *     returns 1: 'Kevin van Zonneveld!'
    // *     example 2: urldecode('http%3A%2F%2Fkevin.vanzonneveld.net%2F');
    // *     returns 2: 'http://kevin.vanzonneveld.net/'
    // *     example 3: urldecode('http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a');
    // *     returns 3: 'http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'
    
    var histogram = {}, histogram_r = {}, code = 0, str_tmp = [];
    var ret = str.toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The histogram is identical to the one in urlencode.
    histogram['!']   = '%21';
    histogram['%20'] = '+';
    
    for (replace in histogram) {
        search = histogram[replace]; // Switch order when decoding
        ret = replacer(search, replace, ret) // Custom replace. No regexing   
    }
    
    // End with decodeURIComponent, which most resembles PHP's encoding functions
    ret = decodeURIComponent(ret);
 
    return ret;
}


function selectAllCheckboxes(selector) {
	var els = $$(selector);
	
	var numElsChecked = 0;
	for(var i=0; i<els.length; i++) {
		if(els[i].checked) {
			numElsChecked ++;
		}
	}
	
	if(numElsChecked > els.length / 2) {
		var ch = false;
	}else{
		var ch = true;
	}
	
	for(var j=0; j<els.length; j++) {
		els[j].checked = ch;
	}
}


function fillForm(userdetails,formname,formExt){
//used to fill in sended/reciever addresses
	for (key in userdetails){
		if (userdetails.hasOwnProperty(key)) { 
			eval('document.'+formname+'.'+formExt+key+'.value = "'+userdetails[key]+'";');
  		}
	}
}

function confirmParcel(el,mm){
//mm is message, el is element (should be 'this')
//get row id, then grab the tracking number from the table
	var idnum = el.name.split("_",1);
	var trNum=document.getElementById('data_'+idnum).innerHTML;
	val = (el.checked) ? 1 : 0;
	if(val == 1){
		var state = confirm('You have set parcel '+trNum+" as "+mm+".\r\n\r\nThis will inform the sender and receiver by email.\r\nAre you sure you want to do this?");
		
	}else{
		var state = confirm('You have set parcel '+trNum+" as NOT "+mm+".\r\n\r\nA mistake has been made\r\nYou will need to inform the sender and receiver by email manually.\r\nPlease make a note of their details and contact them as soon as possible, to let them know a mistake was made");
	}
	
	if (state){
			var req = new DataRequestor();
			req.addArg(_GET, "value", val);
			req.addArg(_GET, "type", mm);
			req.addArg(_GET, "pID", idnum);
			req.getURL('/modules/ajax_gateway/parcel-checkbox.php');
		//	if(mm == 'arrived' && val == 1){
		//		window.open('/'+trNum+'/q/details-full/','printform','width=800,height=600,scrollbars=yes,resizable=yes,location=yes,left=0,top=0');
		//	}
	
	}else{
	//mistake, they clicked cancel, we switch what they've clicked
		el.checked = !el.checked;
	}
	
}

function copytoall(mode){
	
	src_1 = document.pubs_edit.opening_hours_mon_1_o.selectedIndex;
	src_2 = document.pubs_edit.opening_hours_mon_1_c.selectedIndex;
	src_3 = document.pubs_edit.opening_hours_mon_2_o.selectedIndex;
	src_4 = document.pubs_edit.opening_hours_mon_2_c.selectedIndex;
	
	if(mode == 'opening'){
		var tHrs = new Array("opening");
	} else {
		var tHrs = new Array("delivery");
	}

	
	var days = new Array("mon","tue","wed","thur","fri","sat","sun");
	for (w in tHrs){
		if (tHrs.hasOwnProperty(w)) {
			for (x in days){
				if (days.hasOwnProperty(x)) {
					eval('document.pubs_edit.'+tHrs[w]+'_hours_'+days[x]+'_1_o.selectedIndex = src_1;');
					eval('document.pubs_edit.'+tHrs[w]+'_hours_'+days[x]+'_1_c.selectedIndex = src_2;');
					eval('document.pubs_edit.'+tHrs[w]+'_hours_'+days[x]+'_2_o.selectedIndex = src_3;');
					eval('document.pubs_edit.'+tHrs[w]+'_hours_'+days[x]+'_2_c.selectedIndex = src_4;');
					
					eval('document.pubs_edit.'+tHrs[w]+'_hours_'+days[x]+'_1_o.focus();');
					eval('document.pubs_edit.'+tHrs[w]+'_hours_'+days[x]+'_1_c.focus();');
					eval('document.pubs_edit.'+tHrs[w]+'_hours_'+days[x]+'_2_o.focus();');
					eval('document.pubs_edit.'+tHrs[w]+'_hours_'+days[x]+'_2_c.focus();');
					
				}
			}
		}
	}
}

function isPostcode(postcode){
	//check postcode is valid
	pcExp1 = /^[abcdefghijklmnoprstuwyz]{1}[abcdefghklmnopqrstuvwxy]{0,1}[0-9]{1,2}\s{0,}[0-9]{1}[abdefghjlnpqrstuwxyz]{2}\s{0,}$/i
	pcExp2 = /^[abcdefghijklmnoprstuwyz]{1}[0-9]{1}[abcdefghjkstuw]{1}\s{0,}[0-9]{1}[abdefghjlnpqrstuwxyz]{2}$/i;
	pcExp3 = /^[abcdefghijklmnoprstuwyz]{1}[abcdefghklmnopqrstuvwxy][0-9]{1}[abehmnprvwxy]\s{0,}[0-9]{1}[abdefghjlnpqrstuwxyz]{2}$/i;
	//if valid then return true
	 if (pcExp1.test(postcode) || pcExp2.test(postcode) || pcExp3.test(postcode)){
	 	return true;
	 }else{
	 	return false;
	 }

}

/*
function getPubs(postcode){
	//check postcode is valid
	//if valid then ajax call for list of pubs
	 if (isPostcode(postcode)){
	 	var req = new DataRequestor();
		req.setObjToReplace('mylocal_holder');
		req.getURL('/modules/ajax_gateway/closest-pubs.php?postcode='+postcode);
	 }
}
*/
function isdefined( variable){
    return (typeof(window[variable]) == "undefined")?  false: true;
}

var start_val = '';
var sent_val = '';
var pubDelay;
function getPubsDelay(){
	clearTimeout(pubDelay);
	if(start_val != '' && $('q').value != 'Postcode, town or pub name' && $('q').value.length > 1 && $('q').value == start_val){
	//	console.log('matching '+start_val+':'+$('q').value);
		if(sent_val != start_val){
			getPubs(start_val, '');
			sent_val = start_val;
		}
	}else{
		start_val = $('q').value;
	//	console.log('not matching '+start_val+':'+$('q').value);
		pubDelay = setTimeout("getPubsDelay()", 1500);
	}

}

function getPubs(){
	q = $('q').value;
	if(arguments[0] == 'publican'){
		choice = 'Please select your pub';
		publican = true;	
	}else{
		choice = 'Please select an outlet';
		publican = false;
	}
	if(q.length > 1 && q != 'Postcode, town or pub name'){
		var req = new Request({url:'/modules/ajax_gateway/closest-pubs.php',
						   method: 'get',
						   onSuccess: function(responseText) {
						   		if(responseText.length > 2){
						   			var publist = JSON.decode(responseText);				   		
							   		$('fav_select').getChildren().destroy();
							   		new Element('option').setProperties({value:'',html:choice}).injectInside($('fav_select'));
							   		for (x in publist){
							   			new Element('option').setProperties({value:x,html:publist[x]}).injectInside($('fav_select'));
							   		}
							   		if(!publican){
							   			new Element('option').setProperties({value:'0',html:'Other - not in list'}).injectInside($('fav_select'));
							   		}
							   	}else{
							   		$('fav_select').getChildren().destroy();
							   		new Element('option').setProperties({value:'0',html:'no result - try by postcode?'}).injectInside($('fav_select'));
							   	}
							   	
							   	//alert($('fav_select').options[3].value);
							   	//$('fav_select').options[3].selected = "1";

							}
						});
	
		req.send('q='+q);
	}else{
		//$('fav_select').set('html', 'loading....');
	}
}


function checkVanityAddress(q){
	if(q.length > 4){
	var req = new Request({url:'/modules/ajax_gateway/check-vanity.php',
						   method: 'get',
						   onSuccess: function(responseText) {
								$('addressMessage').set('html', responseText);
								//$('mylocal_holder').set('html', '<p>hi</p>');
							}
						});
	
	req.send('q='+q);
	}	
}


function setFormLocalPub(id, name, signed) {
	$('mylocal').set('value', id);
	$('fav_localDetails').setStyle('border-color','#999999');
	$('mylocal_holder').set('html', urldecode(name));
	$$('input.addPubInputBtn').setStyle('display', 'inline');
	$$('div#fav_searchPubOptions').setStyle('display', 'block');
	
	var signedClass = (signed == 1) ? 'ajaxShowPubNameReg' : 'ajaxShowPubNameNonReg';
	$('fav_localDetails').removeClass('ajaxShowPubNameReg');
	$('fav_localDetails').removeClass('ajaxShowPubNameNonReg');
	
	$('fav_localDetails').addClass(signedClass);
}





function checkFindaLocal(){
	//one of the text inputs must have something in them
	rtn=false;
	els = $$('#findapostcode input[type=text]').getProperty('value');
	els.each(
		function(val, indx){
			if(val!=null && val!=""){
				rtn = true;
			}
		}
	);

	if(rtn==true){
		return true;
	}else{
		alert('Please complete the search form.');
		return false;
	}
}


function trim(str){
	return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

function checkPostcode(field){
	if(!isPostcode(field)){
		alert('Please enter a valid UK postcode');
		return false;
	}else{
		return true;
	}
}

function link_popup(address,rel){
	window.open(address,"uylpopup","location=0,status=1,scrollbars=0,"+rel); 
}




function setLocalSliders(num, ignore_first) {
	var newsSlider = new Array();
	var optionsSlider = new Array();
	var ig = 0;
	
	
	for(var i = 0; i<num; i++) {
		var parent = $('localContainer_'+i);
		
		var news = parent.getElement('ul.localsNewsList');
		var newsControl = parent.getElement('p.localsNewsHead');
		
		var options = parent.getElement('ul.localsOptionsList');
		var optionsControl = parent.getElement('p.localsOptionsHead');
		
		newsSlider[i] = new Fx.Slide(news);
		
		if(ignore_first != undefined && i == 0){
			ig = 1; // leave
		} else {
			ig = 0;
		}
		
		if(ig == 0){
			newsSlider[i].hide();
		}

		newsControl.i = i;
		newsControl.addEvent('click', function() {
											newsSlider[this.i].toggle(); 
											var el = this.getFirst('.arrowImg');
											if(el.getStyle('background-position') == '0px -12px') {
												el.setStyle('background-position', '0px 0px');
											}else{
												el.setStyle('background-position', '0px -12px');
											}
										} );
		
		optionsSlider[i] = new Fx.Slide(options);
		optionsSlider[i].hide();

		optionsControl.i = i;
		optionsControl.addEvent('click', function() {
											optionsSlider[this.i].toggle();
											var el = this.getFirst('.arrowImg');
											if(el.getStyle('background-position') == "0px -12px") {
												//console.log('eeeeeer');
												el.setStyle('background-position', "0px 0px");
											}else{
												el.setStyle('background-position', "0px -12px");
										}} );
		
		
		optionsControl.fireEvent('click');
		
	}
	
}

function setPubNewsSliders(num) {
	var sliders = new Array();
	
	for(var i = 0; i<num; i++) {
		var parent      = $('pubNewsItem_'+i);
		var news        = parent.getElement('div.pubSideNewsCopy div.pubNewsLastLines');
		var newsControl = parent.getElement('div.pubSideNewsCopy a.pubNewsViewFull');
		var newsDate    = $('pubSideNewsDate_'+i);
		
		newsDate.setStyle('display', 'none');
		
		sliders[i] = new Fx.Slide(news);
		sliders[i].hide();
		
		newsControl.i = i;
		newsControl.addEvent('click', function() {
										sliders[this.i].toggle();
										if(sliders[this.i].open) {
											this.set('html', 'view full story');
											$('dots_'+this.i).setStyle('display', 'inline');
											$('pubSideNewsDate_'+this.i).setStyle('display', 'none');
										}else{
											this.set('html', 'hide full story');
											$('dots_'+this.i).setStyle('display', 'none');
											$('pubSideNewsDate_'+this.i).setStyle('display', 'block');
										}
									} );
	}
}


function progressbar(msg){
	this.progress = new Element('div').setProperty('id', 'progressbar').setStyles({display:'block',height:document.window.getScrollSize().y+'px'}).injectInside(document.body);
	tp = document.window.getScroll().y;
	this.rotate = new Element('div').setProperty('id', 'rotator').set('html',msg+'<br />').setStyles({display:'block',top:tp+'px'}).injectInside(document.body);
	this.closer = new Element('a').setProperties({'id':'progressClose','href':'javascript:window.location.reload( false );'}).set('html','cancel').inject(this.rotate,'bottom');
}

function mooImLoad(img_array){
$each(img_array, function(val, index){
	var img = new Image(50,50);
	img.src = val;
}); 
}

function confirmSend(cmsg,pmsg){
	if( confirm(cmsg) ){
		progressbar(pmsg);
		return true;
	}else{
		return false;
	}
	
}

function disableRetailer(){
	var fm = document.forms['sendparcel'];
	var rt = fm.elements['retailer'];
	var ort = fm.elements['other-retailer'];
	if(rt.value != ''){
		ort.disabled=true;
	}else{
		ort.disabled=false;
	}
}

function toggleMapOptions(){
	
	
	if( $('moreOptionsContainer').getStyle('display') == 'none'){
		var myFx = new Fx.Tween('moreOptionsContainer',{duration:800});
		myFx.set('opacity',0);
		myFx.set('display','block');
		myFx.start('opacity',0, 1);
	
	}else{
		var myFx = new Fx.Tween('moreOptionsContainer',{duration:800,onComplete:function(e){$('moreOptionsContainer').setStyle('display','none');}});
		myFx.start('opacity',1, 0);
	
	}
}




function setPubMoreAttributes(){
 	m_attrib = new Fx.Slide('second-set');
 	m_attrib.hide();
	$('more-attributes').addEvent('click', function() {
		m_attrib.toggle();
		if(m_attrib.open) {
			$$('li#more-attributes span').setStyle('background-position', "0px 0px");
		}else{
			$$('li#more-attributes span').setStyle('background-position', "0px -12px");
		}
	});
}

function showHideDiv(obj){
	
	obj = $(obj);
	
	if( $(obj).getStyle('display') == 'none'){
		var myFx = new Fx.Tween(obj,{duration:800});
		myFx.set('opacity',0);
		myFx.set('display','block');
		myFx.start('opacity',0, 1);
	
	}else{
		var myFx = new Fx.Tween(obj,{duration:800,onComplete:function(e){$(obj).setStyle('display','none');}});
		myFx.start('opacity',1, 0);
	
	}
	
	
}

function toggleString(obj, str1, str2){
	obj = $(obj);
	var str = '';
	
	if(obj.get('html') == str1){
		str = str2;
	} else {
		str = str1;
	}
	obj.set('html', str);
}

var isLoading = 0;

function centerLoadingBar(){
    var windowWidth = document.documentElement.clientWidth;
    var windowHeight = document.documentElement.clientHeight;
    var popupHeight = $("loadingBar").getProperty('height');
    var popupWidth = $("loadingBar").getProperty('width');

    //centering
    $("loadingBar").setStyles({
        "position": "absolute",
        "top": (windowHeight/2-popupHeight/2) + 60,
        "left": (windowWidth/2-popupWidth/2) - 100
    });
    
   
    //only need force for IE6

    $("loadingBackground").setStyles({
        "height": windowHeight
    });

}


function showLoadingBar(){
	
	
    if (isLoading == 0){
        centerLoadingBar();

        $("loadingBackground").setStyles({
            "opacity": "0.2",
            "display": "block"
        });
        $("loadingBar").setStyles({
        	"display": "block"
        });
        
       
        isLoading = 1;
    }
}


function hideLoadingBar(){
    if (isLoading == 1){
    	 $("loadingBar").setStyles({
         	"display": "none"
         });
    	 $("loadingBackground").setStyles({
          	"display": "none"
          });
    	 
        isLoading = 0;
    }
}

//**************************************************************************
//Copyright 2007 - 2008 The JSLab Team, Tavs Dokkedahl and Allan Jacobs
//Contact: http://www.jslab.dk/contact.php
//
//This file is part of the JSLab Standard Library (JSL) Program.
//
//JSL is free software; you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation; either version 3 of the License, or
//any later version.
//
//JSL is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program. If not, see <http://www.gnu.org/licenses/>.
//***************************************************************************
//File created 2009-01-28 10:09:31

//Compute the intersection of n arrays
Array.prototype.intersect =
function() {
 if (!arguments.length)
   return [];
 var a1 = this;
 var a = a2 = null;
 var n = 0;
 while(n < arguments.length) {
   a = [];
   a2 = arguments[n];
   var l = a1.length;
   var l2 = a2.length;
   for(var i=0; i<l; i++) {
     for(var j=0; j<l2; j++) {
       if (a1[i] === a2[j])
         a.push(a1[i]);
     }
   }
   a1 = a;
   n++;
 }
 return a.unique();
};

//Return new array with duplicate values removed
Array.prototype.unique =
function() {
 var a = [];
 var l = this.length;
 for(var i=0; i<l; i++) {
   for(var j=i+1; j<l; j++) {
     // If this[i] is found later in the array
     if (this[i] === this[j])
       j = ++i;
   }
   a.push(this[i]);
 }
 return a;
};





