
var DEBUG = false;
var current_prod=1;
var max_products=1; //max products -3 Please remember to change this if you change number of special products. Also change CSS file
var automove=false;
var mov_direction=true;


function Home(){    window.location = "/home";}
function msg(s){if (DEBUG) { alert(s); }}
function isValidEmail(str) {return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);}

function validlogin()
{
	    var ea = $('email');
	    var password = $('password'); 
	    var div = $('asif');	    

        return true;
	       
        try  {
            if (ea.value == '') { div.innerHTML = "You have not entered your email address"; return false; }
            if (!isValidEmail(ea.value))  {div.innerHTML = "Your email address is not in a valid format."; return false;}  
            if((password.value == '')){div.innerHTML = "You have not entered your password"; return false;}
                 
            //TODO AJAX Call to get login details 
            return true;      
        }
        catch (e) { alert("error valid login " + e); return false; }
}

function move_left()
{
    try {
	    if(current_prod < max_products)
	    {
		    var currid="sop"+current_prod+"";
		    var curr_prod=document.getElementById(currid);
		    new_prod_idnumber=current_prod+4;
		    var newprodid="sop"+new_prod_idnumber+"";
		    new_prod=document.getElementById(newprodid);
		    curr_prod.style.display="none";
		    new_prod.style.display="block";	
		    current_prod +=1;
	    }	
	}catch(e) { alert("error:move_left() " + e.message); }
}

function move_right()
{
    try 
    {
	    if(current_prod > 1)
	    {
		    old_id_num=current_prod+3;
		    var currid="sop"+old_id_num+"";
		    var curr_prod=document.getElementById(currid);
		    new_prod_idnumber=current_prod-1;
		    var newprodid="sop"+new_prod_idnumber+"";
		    new_prod=document.getElementById(newprodid);
		    curr_prod.style.display="none";
		    new_prod.style.display="block";		
		    current_prod -=1;
	    }
	} catch(e) {    alert("error:move_left() " + e.message); }	
}
function start_automove()
{
	if(current_prod==1)
	{ mov_direction=true;}
	if(current_prod==max_products)
	{ mov_direction=false;}
	if(automove)
	{
	    if(mov_direction)
            { move_left();}
	    else 
	    {   move_right();}
	}
	if(automove && (max_products!=1))
	{	setTimeout('start_automove()',10000);}
}

function showinstorestock(e,wbr_stock,ubs_stock, x, y){
//get x-broswer event target
    var targ;
	if (!e) e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3)
		targ = targ.parentNode;
 
    var ce=targ;
    var px=0;
    var py=0;
    px=getLeftposition(ce);
    py=getTopposition(ce);
    var popdiv;
    if(!(popdiv=$("popup-id")))
    {    popdiv= new Element("div");
         popdiv.set('id','popup-id');
         popdiv.set('class','stock-popup');
    }
    else
    {
        popdiv.innerHTML="";
    }
    
    
    //product -200 & -320
    //listing

    var stylestring="position:absolute;top:"+(py-y)+"px;left:"+(px-x)+"px;";
    //alert(stylestring);
    popdiv.set('style',stylestring);
    
    var swbr_stock;
    if(wbr_stock<=0)
        swbr_stock = "Out of Stock";
    else    
        swbr_stock = "In Stock";
        
    var subs_stock;
    if(ubs_stock<=0)
        subs_stock = "Out of Stock";
    else    
        subs_stock = "In Stock";
        
    var inText=new Element("p");
    inText.innerHTML="<br />Stock available on first come first served basis <br /><br /> <table border='0' cellpadding='0' cellspacing='0' valign='top'><tr valign='top'><td style='width:150px'><strong>Location</strong></td><td><strong>Availability</strong></td></tr><tr valign='top'><td><a class='blue-link' target='_blank' href='http://maps.google.co.uk/maps?f=q&source=s_q&hl=en&geocode=&view=map&q=microdirect++M13+0HR&sll=53.448545,-2.270248&sspn=0.114704,0.363922&ie=UTF8&ll=53.461507,-2.221642&spn=0.00686,0.022745&z=16&iwloc=A'>Upper Brook St., M13 0HR</a></td><td>"+subs_stock+"</td></tr><tr valign='top'><td><a class='blue-link' target='_blank' href='http://maps.google.co.uk/maps?f=q&hl=en&geocode=&q=Weybrook+Road+Manchester+M19+2QD&sll=53.434298,-2.182579&sspn=0.012425,0.027637&ie=UTF8&g=Weybrook+Road+Manchester+M19+2QD&s=AARTsJpcFrQ0sOd14Civ8ADcHHYwKtB5ZQ&view=map&z=16&iwloc=addr'>Weybrook Rd, M19 2QD</a></td><td>"+swbr_stock+"</td></tr></table>";
    inText.set('class','stock-popup-text');
    var close_button=new Element("p");
    close_button.set('class','stock-popup-close');
    //close_button.innerHTML="close";
    close_button.addEvent('click',function(){
                                        var popid=document.getElementById('popup-id');
                                        popid.innerHTML="";
                                        var par_popid=popid.parentNode;
                                        par_popid.removeChild(popid);
                                        });
    popdiv.appendChild(inText);
    popdiv.appendChild(close_button);
    ce.parentNode.appendChild(popdiv);
}

function collectAtStore(e, wbr_stock, ubs_stock) {
    //get x-broswer event target
    var targ;
    if (!e) e = window.event;
    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3)
        targ = targ.parentNode;

    var ce = targ;
    var px = 0;
    var py = 0;
    px = getLeftposition(ce);
    py = getTopposition(ce);
    var popdiv;

    if (!(popdiv = $("popup-id"))) {
        popdiv = new Element("div");
        popdiv.set('id', 'popup-id');
        popdiv.set('class', 'collectatstore-popup');
    }
    else {
        popdiv.innerHTML = "";
    }
    var stylestring = "position:absolute;top:" + (py - 120) + "px;left:" + (px + 10) + "px;";
    //alert(stylestring);
    popdiv.set('style', stylestring);

    var inText = new Element("p");
    inText.innerHTML = "<br /><strong><big>Wish to collect your goods quickly?</big></strong><br /><br />-&nbsp;&nbsp;&nbsp;why not place your order online and collect at one of our Manchester stores - no more queuing...!<br /><br /><strong>Goods can be collected 30 minutes after reserving online and before close of business<br />the next trading day.</strong> We require a telephone number where you can be contacted if necessary.<br /><br /><strong><u>Availability Location:</u></strong><br /><br /><table border='2' cellpadding='0' cellspacing='2' align='center'><tr valign='top'><td style='width:120px'><strong>Where to collect</strong></td><td><strong>&nbsp;&nbsp;Quantity in store&nbsp;&nbsp;</strong></td></tr><tr valign='top'><td><a class='blue-link' target='_blank' href='http://maps.google.co.uk/maps?f=q&source=s_q&hl=en&geocode=&view=map&q=microdirect++M13+0HR&sll=53.448545,-2.270248&sspn=0.114704,0.363922&ie=UTF8&ll=53.461507,-2.221642&spn=0.00686,0.022745&z=16&iwloc=A'>Upper Brook Street Retail Store</a></td><td><strong>" + ubs_stock + "</strong></td></tr><tr valign='top'><td><a class='blue-link' target='_blank' href='http://maps.google.co.uk/maps?f=q&hl=en&geocode=&q=Weybrook+Road+Manchester+M19+2QD&sll=53.434298,-2.182579&sspn=0.012425,0.027637&ie=UTF8&g=Weybrook+Road+Manchester+M19+2QD&s=AARTsJpcFrQ0sOd14Civ8ADcHHYwKtB5ZQ&view=map&z=16&iwloc=addr'>&nbsp;&nbsp;Weybrook Street Warehouse Store&nbsp;&nbsp;</a></td><td><strong>" + wbr_stock + "</strong></td></tr></table><br /><strong><u>How to proceed?</u></strong><br />In order to take advantage of this service, simply add your products to the basket,<br />then choose the <strong>Collect@Store</strong> option on the Basket Checkout page.<br />We will continue to guide you from there.<br /><br />Thank you for your continued business support. We hope this service is of value to you.";
    inText.set('class', 'collectatstore-popup-text');

    var close_button = new Element("p");
    close_button.set('class', 'collectatstore-popup-close');
    //close_button.innerHTML="close";
    close_button.addEvent('click', function() {
        var popid = document.getElementById('popup-id');
        popid.innerHTML = "";
        var par_popid = popid.parentNode;
        par_popid.removeChild(popid);
    });
    popdiv.appendChild(inText);
    popdiv.appendChild(close_button);
    ce.parentNode.appendChild(popdiv);
}

function showavailability(e){
//get x-broswer event target
    var targ;
	if (!e)  e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3)
		targ = targ.parentNode;
 
    var ce=targ;
    var px=0;
    var py=0;
    px=getLeftposition(ce);
    py=getTopposition(ce);
    var popdiv;
    if(!(popdiv=$("apopup-id")))
    {    popdiv= new Element("div");
         popdiv.set('id','apopup-id');
         popdiv.set('class','availability-popup');
    }
    else
    {
        popdiv.innerHTML="";
    }
    var stylestring="position:absolute;top:"+(py+10)+"px;left:"+(px+5)+"px;";
    //alert(stylestring);
    popdiv.set('style',stylestring);
    var inText=new Element("p");
    inText.innerHTML="<strong>Important Notice</strong><br/><br/>This item is currently not in stock. We are accepting orders and this item will be shipped within 5-7 working days.";
    inText.set('class','availability-popup-text');
    var close_button=new Element("p");
    close_button.set('class','availability-popup-close');
    //close_button.innerHTML="close";
    close_button.addEvent('click',function(){
                                        var popid=document.getElementById('apopup-id');
                                        popid.innerHTML="";
                                        var par_popid=popid.parentNode;
                                        par_popid.removeChild(popid);
                                        });
    popdiv.appendChild(inText);
    popdiv.appendChild(close_button);
    ce.parentNode.appendChild(popdiv);
}

function getLeftposition(objE){
 poslft=objE.offsetLeft;
 while(objE.offsetParent!=null){
  pospar=objE.offsetParent;
  poslft+=pospar.offsetLeft;
  objE=pospar;
 }
 return poslft;
}

function getTopposition(objE){
 postop=objE.offsetTop;
 while(objE.offsetParent!=null){
  pospar=objE.offsetParent;
  postop+=pospar.offsetTop;
  objE=pospar;
 }
 return postop;
}

function isNumberPress(even) {
  if (((even > 47 && even < 58) ||
       (even > 95 && even < 106)) && 
       !(even == 8)       || 
       (even == 37) ||
	     (even == 39) || 
       (even == 46) || 
       (even == 8)  || 
       (even == 9))
  {
    return true;
  }
  else
    return false;
}

function noNumbers(e)
{
    var keynum;
    var keychar;
    var numcheck;

    if(window.event) // IE
    {
      keynum = e.keyCode;
    }
    else if(e.which) // Netscape/Firefox/Opera
    {
      keynum = e.which;
    }
    return isNumberPress(keynum);
}

function checkCV2(s)
{
    var i = document.getElementById(s);
    if (i.value.toString() == '')
    {
        alert("Please provide Card Security number");
        return false;
    }
    else { return true; }
}
   
    
       
 document.addEvent('domready', function() {
		
        if(max_products!=1)
            {setTimeout('start_automove()',3000);}
        
        var a = $('jscriptmessage');
		if (a != null) {
            a.set('styles', {display: 'none'});
        }
        
        
        msg("start of domready function");
      
        brandselector();        //brandselector
        tabspane();             //tabspane
        searchfilter();         //searchfilter
        verticalslide();        //vertical slide
        bookmarkproduct();      //bookmark product page
        showlinks();            //show links
        basketdata();           //basket data   
        submitcompare();        //submit compare
        cataloguesearch();      //catalogue search    
        productimages();        //product images
	    formrefresh();          //form refresh
	    //freetext();           //free text search
	    //emailtext();          //email text input
	    //passwordtext();       //password text
	    emailaddress();         //emailaddress
	    qcodetext();            //qcode text
	    security();             //thawte seal and scan alert
	    
	 
	    addressform();          //addressfrom
	    //setloginbox();          //new login box script
	    
	    clearbillingaddress(); // new clear address button functionality
	    cleardeliveryaddress();
	    clearaddeditaddress();
	
	       
	    msg("end of domready function");
		
	});
	
	
//////////////////////////////////////////////////////////////////////////////////
/////////////// Basket funtions calls used in dom ready add event function ///////
/////////////////////////////////////////////////////////////////////////////////
  
	
//////////////////////////////////////////////////////////////////////////////////
////////////////////// funtions calls used in dom ready add event function ///////
/////////////////////////////////////////////////////////////////////////////////



function setloginbox()
{
var lb=null;
 if(lb==$('login-dropdown')) {
    lb.addEvent('click',function (){
        closeloginbox();
        });
 }
 var cb=null;
 if(cb==$('close-login-span')){
    cb.addEvent('click',function (){
        closeloginbox();
    });
 }
}
function closeloginbox()
{
    var lw=null;
        if(lw==$('userlogin')){
            if(lw.hasClass('hide-block')){
                lw.addClass('show-block');
                lw.removeClass('hide-block');
            }
            else
            {
                lw.removeClass('show-block');
                lw.addClass('hide-block');
                //lw.set('style', 'display:none');
            }
        }
}
function brandselector()
{
    var b = $('brandSelector');
	if (b != null) {
		b.addEvent('change', function() {
		    var v = this.options[this.selectedIndex].text;
			location.href = '/Home/Search?attribute_value_string|Brand=' + v;
		});
	}
	
	msg("brand selector is ok");
}

function tabspane()
{
    $$('div.px-tab-pane').each(function(tabPane) {
    var tabs = tabPane.getElements('span.px-tab');
    var panels = tabPane.getElements('div.px-tab-panel');
    tabs.each(function(tab) {
	    tab.addEvent('click', function() {
		    panels.each(function(panel) {
			    panel.removeClass('selected');
		    });

		    var n = 0;
		    tabs.each(function(tab) {
			    tab.removeClass('selected');
			    n++;
		    });
		    this.addClass('selected');
            var myElement = $('showadvanced');
            if(myElement!=null){
            if(this.textContent=="Basic Filters"){
                myElement.value="false"
            }
            else{
                myElement.value="true"
            }
            }
            n = 0;
		    tabs.each(function(tab) {
			    if (tab.hasClass('selected')) {
				    panels[n].addClass('selected');
			    }
			    n++;
		    });

	    });
    });
    });
    
    	msg("tabspane()");
}


function searchfilter()
{
    $$('div.search-filter dt').each(function(twiddle) {
		twiddle.addEvent('click', function() {
			if (this.getParent().hasClass('open')) {
				this.getParent().removeClass('open')
			} else {
				this.getParent().addClass('open')
			}
		});
	});
	
   msg("searchfilter");
}

function verticalslide()
{
   msg("verticalslide()");
}

function bookmarkproduct()
{
	//--Bookamark on Product Page

	var delic=$('delicious');
	if(delic!=null){
	    var delicin=delic.href;
	    var sp=delicin.split('urlhere');
	    delic.href=sp[0]+document.location+sp[1];
	}
	
	delic=$('digg');
	if(delic!=null){
	    var delicin=delic.href;
	    var sp=delicin.split('urlhere');
	    delic.href=sp[0]+document.location+sp[1];
	}
	delic=$('reddit');
	if(delic!=null){
	    var delicin=delic.href;
	    var sp=delicin.split('urlhere');
	    delic.href=sp[0]+document.location+sp[1];
	}
	delic=$('facebook');
	if(delic!=null){
	    var delicin=delic.href;
	    var sp=delicin.split('urlhere');
	    delic.href=sp[0]+document.location+sp[1];
	}
	delic=$('stumblepon');
	if(delic!=null){
	    var delicin=delic.href;
	    var sp=delicin.split('urlhere');
	    delic.href=sp[0]+document.location+sp[1];
	}
	//--Bookmark code end
	
	msg("bookmark product()");
}

function showlinks()
{   
    try {

        var tvp = $('showvatLink');
	    if (tvp != null) {
	        var tp = tvp.href;
	        tvp.href=tp+"?location="+location.pathname+location.search;
	    }
	
	    var tsal = $('showAllLink');
	    if (tsal !=null) {
	        var tp = tsal.href;
	        tsal.href=tp+"?location="+location.pathname+location.search;
	    }
	
	    var tsisl =$('showInStockLink');
	    if (tsisl !=null) {
	        var tp = tsisl.href;
	        tsisl.href=tp+"?location="+location.pathname+location.search;
	    }
	
	}
	catch(e) { msg("error in showlinks " + e); }
	
	msg("showlinks()");
}

function basketdata()
{
  var basketdata = $$('form.add-to-basket');
	basketdata.each(function(form) {
    var tp= form.action;
    form.action=tp+"?location="+location.pathname+location.search;
    });
    
    var basketdatas = $$('form.add-to-baskets');
	basketdatas.each(function(form) {
    var tp= form.action;
    form.action=tp+"?location="+location.pathname+location.search;
    });
    
    msg("basketdata()");
}

function submitcompare()
{

 	var c = null;
 	var str = null;
	if (c = $$('input.submit-compare')) 
	{
		c.addEvent('click', function() {
			var compareArray = [];
			$$('input.compare-product').each(function(opt) {
				if (opt.checked) {
					compareArray.push(opt.get('value'));
				}
			});

			if (compareArray.length > 4) {
				alert('you can only compare up to four products.');
			} else if (compareArray.length > 1) {
			    //alert(compareArray.toString());
				location.href = '/Home/Compare?selected_prod_ids=' + compareArray.toString();
			} else if (compareArray.length == 1) {
				alert('you have only chosen one product to compare, you need at least two.');
			} else {
				alert('you need to choose at least two products to compare.');
			}
			return false;
		});
	}
	
	msg("submitcompare()");
}

function cataloguesearch()
{
	var f = null;
	if (f = $('catalogueSearch')) {
		f.addEvent('submit', function(ev) {
	        var e = new Event(ev).stop();  
			var free_text = this.getElement('#free_text');
			var searchCurrentResults = this.getElement('#searchCurrentResults');
			var href = location.href;
			var href_parts = href.split('?');
			var uri = href_parts[0];
			var url_parts = uri.split('/');
			var querystring = new Hash();
			if (href_parts[1]) {
				qs = href_parts[1].split('&');
				qs.each(function(v) {
					v = v.split('=');
					querystring[v[0]] = v[1];
				});
			}
			
			querystring.free_text = free_text.get('value');
            var standardSearch  = '/Home/Search';
			//if (searchCurrentResults.get('value') == 'In Results') {
			//	location.href = uri + '?' + querystring.toQueryString();
			//} else if (searchCurrentResults.get('value') == 'Whole Site') {
			//	location.href = standardSearch+'?free_text=' + querystring.free_text;
			//} else {
		    //	location.href = standardSearch +'/' +searchCurrentResults.get('value') + '?free_text=' + querystring.free_text;
		    //}
			location.href = standardSearch+'?free_text=' + querystring.free_text;
			return false;
		});
	}	
	
	msg("catalogueSearch()");
}


function productimages()
{
  $$('div.thumbs img').addEvent('mouseover', function() {
		    var view = $$('div#product-main-image img');
		    if (view) {
		               
		        if(this.get('src')!=null&&this.get('src').indexOf('icecat')!=-1){
		        view[0].set('src', this.get('src').replace('thumb', 'low'));
		        }
		        else{
		        view[0].set('src', this.get('src').replace('T_', '').replace('T2_', '').replace('T3_', ''));
		        }
		    }
		});

    msg("productimages()");
}


function formrefresh()
{
    try 
    {  
        msg("formrefresh() 1");
    
        $$('form.refresh').each(function(form) {
            form.addEvent('submit', function(ev) {
                var e = new Event(ev).stop();         
                form.get('send').addEvent('success', function(responseText) {
                    var t = new Element('div');
                    t.set('html', responseText);
                    var c = t.getChildren();
                    if (c[0]) { form.set('html', c[0].get('html')); }
                }.bind(form));
                form.send(); //Sends the form.		    
                return false;
            });   
        });
    
    msg("formrefresh()");
    
   }
   catch(e) { alert('error in form refresh ' + e); return false; }
}


function freetext()
{
     try 
     {
       msg('start of free text error');
       var ft = $('free_text');
		if(ft != null){
		 ft.value='Enter Keywords / Quick Code';
	     ft.addEvent('click', function(ft) {
	       if(this.value=='Enter Keywords / Quick Code'){this.value=''; }
	       return false;
	     });
		}
	}
	catch (err)
	{
		msg("free text error " + err);
	}		
}

function emailtext()
{
    msg("start of email text");
    var ft = null;
	if(ft == $('email')){
	ft.value='Email...';
	ft.addEvent('click', function(ft){
	        if(this.value=='Email...'){
	        this.value='';
	        }
	        return false;
	    });
	}
	
	msg("end of email text");
}

function passwordtext()
{
    var ft = null;
	if(ft == $('password')){
	ft.value='*****';	
	ft.addEvent('click', function(ft){
	        if(this.value=='*****'){
	        this.value='';
	        }
	        return false;
	    });    
	ft.addEvent('focus', function(ft){
	        if(this.value=='*****'){
	        this.value='';
	        }
	        return false;
	    });
	}
}

function qcodetext()
{
		var ft = $('Qcode_text');
		if(ft != null){
		ft.value='Enter Quick Code';
		
		ft.addEvent('click', function(ft){
		        if(this.value=='Enter Quick Code'){
		        this.value='';
		        }
		        return false;
		    });
		}
}

function emailaddress()
{
    var ea =  $('EmailAddress');
	if(ea !=null){
	ea.value='Enter email address';
	
	ea.addEvent('click', function(ea){
	        if(this.value=='Enter email address'){
	        this.value='';
	        }
	        return false;
	    });
	}
}

function security()
{
    if ($("thawteseal")!==null)
    {          
        var doThawteSeal = function(targetObject) {
        // show thawte seal code w/o the reference to their exe in a dom compliant way
        
        var thawtesealLoc = "https://seal.verisign.com/splash?form_file=fdf/splash.fdf&dn=WWW.MICRODIRECT.CO.UK&lang=en";
        new  Asset.image("https://www.microdirect.co.uk/i/verisign.jpg", {id: 'verisignimage'})
            .inject(targetObject).addClass("cur").set("title", "click to verify").addEvent("click", function() {
                window.open(thawtesealLoc,'','height=500,width=545,scrollbars=yes,status=1');
            });
        
        } // end doSeal

      // embed it...
      doThawteSeal($("thawteseal"));
   }
   if($("scanalertseal")!==null)
   {         
      var doScanAlertSeal = function(targetObject) {
      // show scanalert seal code w/o the reference to their exe in a dom compliant way
      var scanalertsealLoc = "https://www.mcafeesecure.com/RatingVerify?ref="+this.location.hostname ;
      new Asset.image("https://images.scanalert.com/meter/www.microdirect.co.uk/13.gif", {id: 'scanalertsealimage'})
            .inject(targetObject).addClass("cur").set("title", "click to verify").addEvent("click", function() {
                window.open(scanalertsealLoc,'Scan_Alert','height=500,width=516,scrollbars=yes,status=1');
            });
     } // end doSeal

     // embed it...
     doScanAlertSeal($("scanalertseal"));
   }

}


		        
		  

function addressform()
{

  		$$('div.address-form').each(function(form) {
  		
		    var psfinder = (form.getElements('input.postcodefind') || [])[0];
		    var resp = document.getElementById('postcode-temperror');
		        if(resp!=null){resp.innerHTML="";}
		        
		    if (psfinder != null) 
		    {		        
		        var addr = {};		        
		        addr.name = (form.getElements('input.name') || [])[0];
		        addr.addressline1 = (form.getElements('input.addressline1') || [])[0];
		        addr.addressline2 = (form.getElements('input.addressline2') || [])[0];
		        addr.city = (form.getElements('input.city') || [])[0];
		        addr.county = (form.getElements('input.county') || [])[0];
		        addr.postcode = (form.getElements('input.postcode') || [])[0];
		        addr.postcodebutton = (form.getElements('input.postcodefind') || [])[0];
		        addr.addchooser = (form.getElements('select.addchooser') || [])[0];
		        
		        var actBlock = psfinder.retrieve('psfinder:clickBlock', function(ev){
		            var e = new Event(ev).stop();  
		            alert('Please select your address from the list.');
	                return false;
		        });
		        
		        var act = psfinder.retrieve('psfinder:click', function(ev){
		            var e = new Event(ev).stop();
		            
   
		            if (addr.postcode.get('value') != '') {		        
		                var url = '/postcode/index?postcode=' + addr.postcode.get('value');
		                

		                
		                var remote = new Request.JSON({'url': url, onComplete: function(address_list) {	
		                    if (address_list != undefined&&address_list.length>0) {
		                    chooser=document.getElementById('addchooser');
		                    if(chooser==null)
		                    {
		                        var chooser = new Element('select').addClass('address-chooser');
		                        chooser.set('id','addchooser');
		                        
		                        addr.name.set('value', '');
                                addr.addressline1.set('value', '');
                                addr.addressline2.set('value', '');
                                addr.city.set('value', '');
                                addr.county.set('value', '');
                            }
		                    else
		                    {
		                        chooser.innerHTML="";
		                    }    
		                        chooser.adopt(new Element('option', {'value':'', 'html':'Please Choose...'}));
	                            address_list.each(function(address) {
                                    var RMAddress = new RoyalMailAddress(address);   
	                                chooser.adopt(new Element('option', {'value':RMAddress.address_key(), 'html':((RMAddress.companyname() != '' ? RMAddress.companyname() + ', ' : '') + RMAddress.addressline1() + ' ' + RMAddress.addressline2()) }));
	                            });
            		            
	                            chooser.addEvent('change', function() {
	                                address_list.each(function(address) {
                                        var RMAddress = new RoyalMailAddress(address);   
	                                    if (RMAddress.address_key() == chooser.get('value')) {
	                                        addr.name.set('value', RMAddress.companyname());
	                                        addr.addressline1.set('value', RMAddress.addressline1());
	                                        addr.addressline2.set('value', RMAddress.addressline2());
	                                        addr.city.set('value', RMAddress.city());
	                                        addr.county.set('value', RMAddress.county());
	                                        addr.postcode.set('value', RMAddress.postcode());
                		                    
	                                        chooser.destroy();
	                                        addr.addressline1.set('styles', {display: ''});
		        
		                                    psfinder.removeEvent('click', actBlock);
		                                    psfinder.addEvent('click', act);
	                                    }
	                                });
	                            });
            		                    		    
                                chooser.inject(addr.addressline1, 'before');
                                
                                if(resp!=null){resp.innerHTML="";}
                                addr.addressline1.set('styles', {display: 'none'});
		                        
                            } else {
                                
                                if(resp==null)
                                {
                                    resp = new Element('span').addClass('field-validation-error');
                                }
                                else
                                {
                                    resp.innerHTML="";
                                }
                                resp.set('id','postcode-temperror');
                                resp.set('styles',{ display: 'block'});
                                resp.set('styles',{ clear: 'both'});
                                var p1= new Element('span');
                                p1.innerHTML="Cannot find address. ";
                                resp.appendChild(p1);
                               
                                //retry link
                                var retrylink= new Element('span');
                                retrylink.set('styles',{ cursor: 'pointer'});
                                retrylink.set('styles',{ textDecoration: 'underline'});
                                retrylink.addEvent('click',function(){
                                                                    addr.postcode.set('value','');
                                                                    addr.postcode.focus();
                                });
                                retrylink.set('title','Retry Postcode');
                                retrylink.innerHTML="Retry";
                                resp.appendChild(retrylink);
                                // or between retry and manual entry
                                var p2= new Element('span');
                                p2.innerHTML=" or ";
                                resp.appendChild(p2);
                                
                                //Enter address manually link
                                var addresslink= new Element('span');
                                addresslink.set('styles',{ cursor: 'pointer'});
                                addresslink.set('styles',{ textDecoration: 'underline'});
                                addresslink.addEvent('click',function(){
                                                                    addr.addressline1.set('value','');
                                                                    addr.addressline1.focus();
                                });
                                addresslink.set('title','Enter Address Manually');
                                addresslink.innerHTML="Enter address manually";
                                resp.appendChild(addresslink);
                                
                                resp.inject(addr.postcodebutton,'after');
                               
                                
                                
                            }
		                }}).send();
		            } else {
		                alert('You need to enter a valid postcode first');
		            }
	                
	                return false;
		        });
		        
		        psfinder.addEvent('click', act);
		    }   //end of if 
        });  //end of div-address form function
}


/////////////////////////////////////////////////////////////////////////////////////////
///////  clear billing / delivery address fields ////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////

function clearaddeditaddress()
{
 var addr = {};	
      var addressline1, addressline2, city , county,postcode, chooser;       
      var ea = $('btnAddEditAddressClear'); 
      if (ea != null) {
        $$('div.address-form').each(function(form) {  
            try  {
                    addressline1 = document.getElementById("LineOne");
                    addressline2 = document.getElementById("LineTwo");
                    city = document.getElementById("TownCity");
                    county = document.getElementById("County");
                    postcode = document.getElementById("Postcode");
		 
                    chooser = document.getElementById("addchooser");
                 	       
                } catch (e) { alert("error" + e);}
        });  

        ea.addEvent('click', function(ea){ 
               if (addressline1 != null) { addressline1.value = ''; addressline1.set('style','display:block'); }
               if (addressline2 != null) { addressline2.value = '';}
               if (city != null) { city.value = ''; }
               if (county != null) { county.value = '';  }
    	       if (postcode != null) { postcode.value = ''; }
               if (chooser != null) {  chooser.set('style', 'display:none'); }
               return false;
        });
    }
}

function clearbillingaddress()
{      
      var addr = {};	
      var addressline1, addressline2, city , county,postcode, chooser;       
      var ea = $('btnBillingClear');
      if (ea != null)
      {
        $$('div.address-form').each(function(form) {  
            try  {
                    addressline1 = document.getElementById("BillingAddress_LineOne");
                    addressline2 = document.getElementById("BillingAddress_LineTwo");
                    city = document.getElementById("BillingAddress_TownCity");
                    county = document.getElementById("BillingAddress_County");
                    postcode = document.getElementById("BillingAddress_Postcode");
                    chooser = document.getElementById("addchooser");
                 	       
                } catch (e) { alert("error" + e);}
        });  

        ea.addEvent('click', function(ea){ 
               if (addressline1 != null) { addressline1.value = ''; addressline1.set('style','display:block'); }
               if (addressline2 != null) { addressline2.value = '';}
               if (city != null) { city.value = ''; }
               if (county != null) { county.value = ''; }
	           if (postcode != null) { postcode.value = ''; }
               if (chooser != null) { chooser.set('style', 'display:none'); alert('hide chooser billing');   }
               return false;
        });
    }
}

function cleardeliveryaddress()
{
  var addr = {};	
      var addressline1, addressline2, city , county,postcode, chooser;       
      var ea = $('btnDeliveryClear');   
      if (ea != null) { 
        $$('div.address-form').each(function(form) {  
            try  {
                    addressline1 = document.getElementById("DeliveryAddress_LineOne");
                    addressline2 = document.getElementById("DeliveryAddress_LineTwo");
                    city = document.getElementById("DeliveryAddress_TownCity");
                    county = document.getElementById("DeliveryAddress_County");
                    postcode = document.getElementById("DeliveryAddress_Postcode");
                    chooser = document.getElementById("addchooser");
                 	       
                } catch (e) { alert("error" + e);}
        });  

        ea.addEvent('click', function(ea){ 
               if (addressline1 != null) { addressline1.value = ''; addressline1.set('style','display:block'); }
               if (addressline2 != null) { addressline2.value = '';}
               if (city != null) { city.value = ''; }
               if (county != null) { county.value = ''; }
               if (postcode != null) { postcode.value = ''; }
               if (chooser != null){  chooser.set('style', 'display:none');  }
               return false;
        });
       
      }
}
	
//////////////////////////////////////////////////////////////////////////////////
////////////////////// helper funtions ///////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
   	
	var RoyalMailAddress = new Class({
	
	    initialize: function (data) {
	        this.data = data;
	    },
	
	    address_key: function() {
	        return (this.data.Address_Key != null ? ('' + this.data.Address_Key).trim() : '');
	    },
	    
	    companyname: function() {
	        var temp = (this.data.Large_Organisation_Name != null ? ('' + this.data.Large_Organisation_Name).trim() + ' ' : ''); 
	        if (this.data.Small_Organisation_Name != null) temp += ('' + this.data.Small_Organisation_Name);
	        return  temp.trim();                            
	    },
	
	    building_no: function() {
	        return (this.data.Building_No != null ? ('' + this.data.Building_No).trim() : ''); 
	    },
	    
	    addressline1: function() {
	        var temp = '';	    
	        
	        var subBuildingName = '';
	        var buildingName = '';
	        if(this.data.Sub_Building_Name != null) subBuildingName = this.data.Sub_Building_Name;
	        if(this.data.Building_Name != null) buildingName = this.data.Building_Name;
	        
	        if (subBuildingName.trim() + buildingName.trim() != ''){
	            temp = subBuildingName.trim() + ' ' + buildingName.trim();
	        }
	        else{
	            if (this.building_no() != null) temp = this.building_no() + ' ';
	            if (this.data.Street_Name1 != null) temp += ('' + this.data.Street_Name1).trim() + ' ';
	            if (this.data.Street_Name2 != null) temp += ('' + this.data.Street_Name2).trim() + ' ';
	            if (this.data.Street_Description1 != null) temp += ('' + this.data.Street_Description1).trim() + ' ';
	            if (this.data.Street_Description2 != null) temp += ('' + this.data.Street_Description2);
	        }

	        return  temp.trim();                            
	    },
	    
	    addressline2: function() {
	        var temp = '';
	        
	        var subBuildingName = '';
	        var buildingName = '';
	        if(this.data.Sub_Building_Name != null) subBuildingName = this.data.Sub_Building_Name;
	        if(this.data.Building_Name != null) buildingName = this.data.Building_Name;
	        
	        if (subBuildingName.trim() + buildingName.trim() != ''){
	            if (this.building_no() != null) temp = this.building_no() + ' ';
	            if (this.data.Street_Name1 != null) temp += ('' + this.data.Street_Name1).trim() + ' ';
	            if (this.data.Street_Name2 != null) temp += ('' + this.data.Street_Name2).trim() + ' ';
	            if (this.data.Street_Description1 != null) temp += ('' + this.data.Street_Description1).trim() + ' ';
	            if (this.data.Street_Description2 != null) temp += ('' + this.data.Street_Description2);
	            if (this.data.Dependant_Locality != null)  temp += ('' + this.data.Dependant_Locality);
	        }
	        else{
	            if (this.data.Dependant_Locality != null)  temp += ('' + this.data.Dependant_Locality);
	        }
	        
            return  temp.trim();                            
	    },
	    
	    city: function() {            
	        return (this.data.Post_Town != null ? ('' + this.data.Post_Town).trim() : '');             
	    },
	    
	    county: function() {                        
	        return (this.data.County != null ? ('' + this.data.County).trim() : '');  
	    },
	    
	    postcode: function() {
	        if (this.data.Post_Code != null)
	        {
	            var sPostcode = this.data.Post_Code.split(' ').join('');
	            var inCode = sPostcode.substring(sPostcode.length - 3,sPostcode.length);
	            var outCode = sPostcode.substring(0,sPostcode.length - 3);
	            return ('' + (outCode + ' ' + inCode)).trim();
	        }
	        else
	            return '';
	    }
	});
	
	var address_list = [
{
    "Address_Key":8666423,
    "Large_Organisation_Dept_Name":null,
    "Large_Organisation_Name":null,
    "PO_Box_No":null,
    "Small_Organisation_Dept_Name":null,
    "Small_Organisation_Name":null,
    "Sub_Building_Name":null,
    "Building_Name":null,
    "Building_No":10,
    "Street_Name1":"STAMFORD                                                    ",
    "Street_Description1":"STREET              ",
    "Street_Name2":null,
    "Street_Description2":null,
    "DblDependant_Locality":null,
    "Dependant_Locality":null,
    "Post_Town":"MANCHESTER                    ",
    "County":"LANCASHIRE",
    "Post_Code":"M16 9JQ"
},
{"Address_Key":8666424,
"Large_Organisation_Dept_Name":null,
"Large_Organisation_Name":null,"PO_Box_No":null,"Small_Organisation_Dept_Name":null,"Small_Organisation_Name":null,"Sub_Building_Name":null,"Building_Name":null,"Building_No":12,"Street_Name1":"STAMFORD                                                    ","Street_Description1":"STREET              ","Street_Name2":null,"Street_Description2":null,"DblDependant_Locality":null,"Dependant_Locality":null,"Post_Town":"MANCHESTER                    ","County":"LANCASHIRE","Post_Code":"M16 9JQ"},
{"Address_Key":8666425,
"Large_Organisation_Dept_Name":null,
"Large_Organisation_Name":null,"PO_Box_No":null,"Small_Organisation_Dept_Name":null,"Small_Organisation_Name":null,"Sub_Building_Name":null,"Building_Name":null,"Building_No":14,"Street_Name1":"STAMFORD                                                    ","Street_Description1":"STREET              ","Street_Name2":null,"Street_Description2":null,"DblDependant_Locality":null,"Dependant_Locality":null,"Post_Town":"MANCHESTER                    ","County":"LANCASHIRE","Post_Code":"M16 9JQ"},
{"Address_Key":8666426,
"Large_Organisation_Dept_Name":null,
"Large_Organisation_Name":null,"PO_Box_No":null,"Small_Organisation_Dept_Name":null,"Small_Organisation_Name":null,"Sub_Building_Name":null,"Building_Name":null,"Building_No":16,"Street_Name1":"STAMFORD                                                    ","Street_Description1":"STREET              ","Street_Name2":null,"Street_Description2":null,"DblDependant_Locality":null,"Dependant_Locality":null,"Post_Town":"MANCHESTER                    ","County":"LANCASHIRE","Post_Code":"M16 9JQ"},
{"Address_Key":8666427,
"Large_Organisation_Dept_Name":null,
"Large_Organisation_Name":null,"PO_Box_No":null,"Small_Organisation_Dept_Name":null,"Small_Organisation_Name":null,"Sub_Building_Name":null,"Building_Name":null,"Building_No":18,"Street_Name1":"STAMFORD                                                    ","Street_Description1":"STREET              ","Street_Name2":null,"Street_Description2":null,"DblDependant_Locality":null,"Dependant_Locality":null,"Post_Town":"MANCHESTER                    ","County":"LANCASHIRE","Post_Code":"M16 9JQ"},
{"Address_Key":8666428,
"Large_Organisation_Dept_Name":null,
"Large_Organisation_Name":null,"PO_Box_No":null,"Small_Organisation_Dept_Name":null,"Small_Organisation_Name":null,"Sub_Building_Name":null,"Building_Name":null,"Building_No":20,"Street_Name1":"STAMFORD                                                    ","Street_Description1":"STREET              ","Street_Name2":null,"Street_Description2":null,"DblDependant_Locality":null,"Dependant_Locality":null,"Post_Town":"MANCHESTER                    ","County":"LANCASHIRE","Post_Code":"M16 9JQ"},
{"Address_Key":8666429,
"Large_Organisation_Dept_Name":null,
"Large_Organisation_Name":null,"PO_Box_No":null,"Small_Organisation_Dept_Name":null,"Small_Organisation_Name":null,"Sub_Building_Name":null,"Building_Name":null,"Building_No":22,"Street_Name1":"STAMFORD                                                    ","Street_Description1":"STREET              ","Street_Name2":null,"Street_Description2":null,"DblDependant_Locality":null,"Dependant_Locality":null,"Post_Town":"MANCHESTER                    ","County":"LANCASHIRE","Post_Code":"M16 9JQ"},
{"Address_Key":8666430,
"Large_Organisation_Dept_Name":null,
"Large_Organisation_Name":null,"PO_Box_No":null,"Small_Organisation_Dept_Name":null,"Small_Organisation_Name":null,"Sub_Building_Name":null,"Building_Name":null,"Building_No":24,"Street_Name1":"STAMFORD                                                    ","Street_Description1":"STREET              ","Street_Name2":null,"Street_Description2":null,"DblDependant_Locality":null,"Dependant_Locality":null,"Post_Town":"MANCHESTER                    ","County":"LANCASHIRE","Post_Code":"M16 9JQ"},
{"Address_Key":8666431,
"Large_Organisation_Dept_Name":null,
"Large_Organisation_Name":null,"PO_Box_No":null,"Small_Organisation_Dept_Name":null,"Small_Organisation_Name":null,"Sub_Building_Name":null,"Building_Name":null,"Building_No":26,"Street_Name1":"STAMFORD                                                    ","Street_Description1":"STREET              ","Street_Name2":null,"Street_Description2":null,"DblDependant_Locality":null,"Dependant_Locality":null,"Post_Town":"MANCHESTER                    ","County":"LANCASHIRE","Post_Code":"M16 9JQ"},
{"Address_Key":8666432,
"Large_Organisation_Dept_Name":null,
"Large_Organisation_Name":null,"PO_Box_No":null,"Small_Organisation_Dept_Name":null,"Small_Organisation_Name":null,"Sub_Building_Name":null,"Building_Name":null,"Building_No":28,"Street_Name1":"STAMFORD                                                    ","Street_Description1":"STREET              ","Street_Name2":null,"Street_Description2":null,"DblDependant_Locality":null,"Dependant_Locality":null,"Post_Town":"MANCHESTER                    ","County":"LANCASHIRE","Post_Code":"M16 9JQ"},
{"Address_Key":8666433,
"Large_Organisation_Dept_Name":null,
"Large_Organisation_Name":null,"PO_Box_No":null,"Small_Organisation_Dept_Name":null,"Small_Organisation_Name":null,"Sub_Building_Name":null,"Building_Name":null,"Building_No":30,"Street_Name1":"STAMFORD                                                    ","Street_Description1":"STREET              ","Street_Name2":null,"Street_Description2":null,"DblDependant_Locality":null,"Dependant_Locality":null,"Post_Town":"MANCHESTER                    ","County":"LANCASHIRE","Post_Code":"M16 9JQ"},
{"Address_Key":8666434,
"Large_Organisation_Dept_Name":null,
"Large_Organisation_Name":null,"PO_Box_No":null,"Small_Organisation_Dept_Name":null,"Small_Organisation_Name":null,"Sub_Building_Name":null,"Building_Name":null,"Building_No":32,"Street_Name1":"STAMFORD                                                    ","Street_Description1":"STREET              ","Street_Name2":null,"Street_Description2":null,"DblDependant_Locality":null,"Dependant_Locality":null,"Post_Town":"MANCHESTER                    ","County":"LANCASHIRE","Post_Code":"M16 9JQ"},
{"Address_Key":8666435,
"Large_Organisation_Dept_Name":null,
"Large_Organisation_Name":null,"PO_Box_No":null,"Small_Organisation_Dept_Name":null,"Small_Organisation_Name":null,"Sub_Building_Name":null,"Building_Name":null,"Building_No":34,"Street_Name1":"STAMFORD                                                    ","Street_Description1":"STREET              ","Street_Name2":null,"Street_Description2":null,"DblDependant_Locality":null,"Dependant_Locality":null,"Post_Town":"MANCHESTER                    ","County":"LANCASHIRE","Post_Code":"M16 9JQ"},
{"Address_Key":8666436,
"Large_Organisation_Dept_Name":null,
"Large_Organisation_Name":null,"PO_Box_No":null,"Small_Organisation_Dept_Name":null,"Small_Organisation_Name":null,"Sub_Building_Name":null,"Building_Name":null,"Building_No":36,"Street_Name1":"STAMFORD                                                    ","Street_Description1":"STREET              ","Street_Name2":null,"Street_Description2":null,"DblDependant_Locality":null,"Dependant_Locality":null,"Post_Town":"MANCHESTER                    ","County":"LANCASHIRE","Post_Code":"M16 9JQ"},
{"Address_Key":8666437,
"Large_Organisation_Dept_Name":null,
"Large_Organisation_Name":null,"PO_Box_No":null,"Small_Organisation_Dept_Name":null,"Small_Organisation_Name":null,"Sub_Building_Name":null,"Building_Name":null,"Building_No":38,"Street_Name1":"STAMFORD                                                    ","Street_Description1":"STREET              ","Street_Name2":null,"Street_Description2":null,"DblDependant_Locality":null,"Dependant_Locality":null,"Post_Town":"MANCHESTER                    ","County":"LANCASHIRE","Post_Code":"M16 9JQ"},
{"Address_Key":8666438,
"Large_Organisation_Dept_Name":null,
"Large_Organisation_Name":null,"PO_Box_No":null,"Small_Organisation_Dept_Name":null,"Small_Organisation_Name":null,"Sub_Building_Name":null,"Building_Name":null,"Building_No":40,"Street_Name1":"STAMFORD                                                    ","Street_Description1":"STREET              ","Street_Name2":null,"Street_Description2":null,"DblDependant_Locality":null,"Dependant_Locality":null,"Post_Town":"MANCHESTER                    ","County":"LANCASHIRE","Post_Code":"M16 9JQ"},
{"Address_Key":8666439,
"Large_Organisation_Dept_Name":null,
"Large_Organisation_Name":null,"PO_Box_No":null,"Small_Organisation_Dept_Name":null,"Small_Organisation_Name":null,"Sub_Building_Name":null,"Building_Name":null,"Building_No":42,"Street_Name1":"STAMFORD                                                    ","Street_Description1":"STREET              ","Street_Name2":null,"Street_Description2":null,"DblDependant_Locality":null,"Dependant_Locality":null,"Post_Town":"MANCHESTER                    ","County":"LANCASHIRE","Post_Code":"M16 9JQ"},
{"Address_Key":8666440,
"Large_Organisation_Dept_Name":null,
"Large_Organisation_Name":null,"PO_Box_No":null,"Small_Organisation_Dept_Name":null,"Small_Organisation_Name":null,"Sub_Building_Name":null,"Building_Name":null,"Building_No":44,"Street_Name1":"STAMFORD                                                    ","Street_Description1":"STREET              ","Street_Name2":null,"Street_Description2":null,"DblDependant_Locality":null,"Dependant_Locality":null,"Post_Town":"MANCHESTER                    ","County":"LANCASHIRE","Post_Code":"M16 9JQ"}
    ];

