// **********************************************************************************************************************
// Google Map Functions
// **********************************************************************************************************************

var map;
var geocoder;

function load() {
    if (GBrowserIsCompatible()) {
        geocoder = new GClientGeocoder();
        map = new GMap2(document.getElementById('map_container'));
        map.addControl(new GLargeMapControl3D());
        map.addControl(new GMapTypeControl());
        if ($('location') && ($('location').get('value') != '')) {
	        var address = $('location').get('value');
	        address = address + ", London, UK";
	
	        geocoder.getLatLng(address, function(latlng) {
	            (!latlng) 
	            ? alert(address + ' not found') 
	            : map.setCenter(new GLatLng(latlng.lat(), latlng.lng()), 14);
	        });
        } else {
        	map.setCenter(new GLatLng(51.51333, -0.088947), 14);
        }
    }
}

function buildURL() {
    var tempurl = "/my_wedge/?";

    if ($('location') && ($('location').get('value') != '' && $('location').get('value') != 'undefined')) { 
        tempurl = tempurl + '&location=' + encodeURIComponent($('location').get('value'));
        
    }
    if ($('category') && ($('category').get('value') != '' && $('category').get('value') != 'undefined')) {
    	if ($('category').get('value') == '8') {//Empty location (where) when Online Only is selected 
    		$('location').set('value', '');
    	} else {
    		//if ($('keytags') && ($('keytags').get('value') != '' && $('category').get('value') != '0'))
    		//$('category').set('value', '0');
    	}
    	tempurl = tempurl + '&category=' + encodeURIComponent($('category').get('value'));
    }

    if ($('keytags') && ($('keytags').get('value') != '' && $('keytags').get('value') != 'undefined')) {
        tempurl = tempurl + '&keytags=' + encodeURIComponent($('keytags').get('value'));
    }

    if ($('start') && ($('start').get('value') != '' && $('start').get('value') != 'undefined')) {
        tempurl = tempurl + '&start=' + encodeURIComponent($('start').get('value'));
    }
    
    window.location = tempurl;
        
}

function myLocation(location) {
	if (location != '' || location != 'undefined')  
		$('location').set('value', location);
}

function searchLocations() {
    var address = $('location').get('value');
    //CHECK for RBKC areas and append appropriate suffixes
    switch (address.toLowerCase()) {
    	case 'worlds end':
    		address = address + ' estate, London SW10';
    		break;
    	case "world's end":
    		address = address + ' estate, London SW10';
    		break;
    	case 'knightsbridge':
    		address = address + ' tube station, Kensington';
    		break;
    	case 'holland park':
    		address = address + ' tube station, Kensington';
    		break;
    	case 'notting hill':
    		address = address + ' Gate tube station, Kensington';
    		break;
    	case 'notting hill gate':
    		address = address + ' tube station, Kensington';
    		break;
    	case 'kensington church street':
    		address = address + ', Kensington, London W8';
    		break;
    	case 'kensington church st':
    		address = address + ', Kensington, London W8';
    		break;
    }
    
    if (address.search(/london/i) == -1) {    
    	address = address + ", London";
    }
    address = address + ", UK";
    //alert(address);    
    geocoder.getLatLng(address, function(latlng) {
        (!latlng) 
        ? alert(address + ' not found') 
        : searchLocationsNear(latlng);
    });
}

function checkLocation() {
	// On location focus - reset category value to everything if 'Online Only' had been selected 
	if ($('category') && $('category').get('value') == '8') {
		$('category').set('value', '0');
	}
}

function merchant_map(GLat, GLng) { 
      if (GBrowserIsCompatible()) { 
        var map = new GMap2(document.getElementById("map_container_small")); 
		
		map.setCenter(new GLatLng(GLat, GLng), 14);
        //map.addControl(new GSmallMapControl());
		var baseIcon = new GIcon(G_DEFAULT_ICON); 
		baseIcon.shadow = "/assets/front/wedge_pointershadow30x30.png"; 
		baseIcon.iconSize = new GSize(30, 30); 
		baseIcon.shadowSize = new GSize(37, 30); 
		baseIcon.iconAnchor = new GPoint(9, 30); 
		baseIcon.infoWindowAnchor = new GPoint(9, 2);
		var letteredIcon = new GIcon(baseIcon); 
		letteredIcon.image = "/assets/front/wedge_pointer30x30.png"; 		
		markerOptions = { icon:letteredIcon }; 
		var marker = new GMarker(new GLatLng(GLat, GLng), markerOptions); 
        map.addOverlay(marker);
        //marker.openInfoWindowHtml("");
		
        map.setUIToDefault(); 
      } 
}

function searchLocationsNear(center) {
    // Create a base icon for all of our markers that specifies the
    // shadow, icon dimensions, etc.
	// Filter out online only bizs to speed up GMaps 
    var baseIcon = new GIcon(G_DEFAULT_ICON);
    baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
    baseIcon.iconSize = new GSize(20, 34);
    baseIcon.shadowSize = new GSize(37, 34);
    baseIcon.iconAnchor = new GPoint(9, 34);
    baseIcon.infoWindowAnchor = new GPoint(9, 2);
    
    //var radius = document.getElementById('radiusSelect').value;
    var radius = "8"; //radius of miles from point/location on map (Increasing this value also increases overall results found)
    
    var category = $('category').get('value');
    var keytags = $('keytags').get('value');
    var loc = $('location').get('value');
    var start = $('start').get('value');
    //if (start == "") start = 0;
    
    var searchUrl = '/map_location/?location=' + loc + '&lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius  + '&keytags=' + keytags + '&category=' + category + '&start=' + start;
    
    GDownloadUrl(searchUrl, function(data) {
        var xml = GXml.parse(data);
        var markers = xml.getElementsByTagName('marker');
        map.clearOverlays();
        
        var sidebar = document.getElementById('merchant_list');
        sidebar.innerHTML = '';
        if (markers.length == 0) {
            sidebar.innerHTML = '<div id="wp_noresults"><img src="../assets/global/search_warning_32.gif"><h3>Sorry,<br>No businesses found.</h3><hr><h4 class="bottom">Are you a business?</h4>Joining Wedge brings many benefits.<br><br><a title="Find out how Wedge card benefits you" id="findouthow_button" href="/wedge_for_businesses"><span class="hide">Find out how</span></a></p></div>';
            map.setCenter(new GLatLng(51.514601, -0.1354507), 10);
            return;
        }
        
        if (category != '8') { //NON ONLINE ONLY
        	var bounds = new GLatLngBounds();  
        	var totalLength = 26; //TOTAL NUMBER OF A-Z MARKERS TO SHOW
        	var total = markers[0].getAttribute('totalcount');
        	//$('result_count').set('html', "showing <strong>" + totalLength + "</strong> nearest");
        } else {
        	var totalLength = 50; //Total number ONLINE ONLY
        	var total = markers[0].getAttribute('totalcount');
        }
        
        //---- show paging bar & paging options for Google Results ----
        var html = "";
        var pagebar = document.getElementById('wmap_pagebar');
        var totalPages = Math.round(total/totalLength); //total number of result pages
        if (totalPages == 0) totalPages = 1;
        var currentPage = (start / totalLength) + 1;
        var nextPage = currentPage * totalLength;
        var prevPage = (start - totalLength);
        var firstPage = 0;
        var lastPage = (totalPages - 1) * totalLength;
        
        html = html + '<ul id="wmap_pages">';

        if (start > 1) {
        	html = html + '<li><a href="#" onclick="doMapPaging(' + firstPage + ');" title="Back to first results" class="start_page_handle">&lt;&lt;</a></li>';
        	if (currentPage > 1) {
        		html = html + '<li><a href="#" onclick="doMapPaging(' + prevPage + ');" title="Previous results" class="start_page_handle">&lt;</a></li>';
        	}
        } else {
            html = html + '<li class="quiet">&lt;&lt;</li><li class="quiet">&lt;</li>'; 
        }
        html = html + '<li>Page ' + currentPage + ' of ' + totalPages + '</li>'
        
        if (currentPage < totalPages) {
        	html = html + '<li><a href="#" onclick="doMapPaging(' + nextPage + ');" title="Next results" class="start_page_handle">&gt;</a></li>';
        	html = html + '<li><a href="#" onclick="doMapPaging(' + lastPage + ');" title="Go to last results" class="start_page_handle">&gt;&gt;</a></li>';
        } else {
            html = html + '<li class="quiet">&gt;</li><li class="quiet">&gt;&gt;</li>'; 
        }
        html = html + '</ul>';
        pagebar.innerHTML = html;
        //-------------------------------------------------------------
        
        // Create marker array   
        if (markers.length <= totalLength) {
            totalLength = markers.length; 
        }
        $('result_count').set('html', "<strong>" + total + "</strong> <span>results by proximity</span>");
        
        for (var i = 0; i < totalLength; i++) {
            var name = markers[i].getAttribute('name');
            var address = markers[i].getAttribute('address');
            var distance = parseFloat(markers[i].getAttribute('distance'));
            var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')), parseFloat(markers[i].getAttribute('lng')));    
            var letter = markers[i].getAttribute('letter');
            //var tel = markers[i].getAttribute('tel');
            var postcode = markers[i].getAttribute('postcode');
            var cat =  markers[i].getAttribute('category');
            var id = markers[i].getAttribute('id');
            var followed = markers[i].getAttribute('followed');
            var disc = markers[i].getAttribute('discount');
            
            // Set up our GMarkerOptions object  
            var letteredIcon = new GIcon(baseIcon);  
            //letteredIcon.image = "http://www.google.com/mapfiles/marker_yellow" + letter + ".png";  
            letteredIcon.image = "http://www.google.com/mapfiles/marker_orange" + letter + ".png";  
            
            //var iconOptions = {}; iconOptions.primaryColor = "#FF66FF"; iconOptions.strokeColor = "#000000"; iconOptions.label = "66"; iconOptions.labelColor = "#ffffff"; iconOptions.addStar = false; iconOptions.starPrimaryColor = "#FFFF00"; iconOptions.starStrokeColor = "#0000FF"; var icon = MapIconMaker.createLabeledMarkerIcon(iconOptions);
            //var iconOptions = {}; iconOptions.primaryColor = "#b80f6a"; iconOptions.strokeColor = "#000000"; iconOptions.label = letter; iconOptions.labelColor = "#ffffff"; iconOptions.addStar = false; iconOptions.starPrimaryColor = "#FFFF00"; iconOptions.starStrokeColor = "#0000FF";
            markerOptions = { icon:letteredIcon };
            
            //Create Map marker only if postcode is available
            if (category != '8') {//NON ONLINE ONLY
            	var marker = createMarker(point, name, address, disc, letter, markerOptions);        
            	map.addOverlay(marker);
            }           
            var sidebarEntry = createSidebarEntry(marker, name, address, postcode, cat, letter, distance, followed);
            sidebar.appendChild(sidebarEntry);
            
            if (category != '8') {//NON ONLINE ONLY 
            	bounds.extend(point); 
            }
        }
        
        $$('a.follow_merchant').each (function(btn, index) {
            add_merchant(btn);
        });
        if (category != '8') { //NON ONLINE ONLY
        	map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
        }
      });
}

function createMarker(point, name, address, disc, letter, markerOptions) {
    var marker = new GMarker(point, markerOptions);
    var link = '<a href="/business/' + encodeURIComponent((name.toLowerCase())) + '?return=true" title="Visit Business homepage">' + name + '</a>';
    var html = "<strong>" + letter + ': ' + link + '</strong><br />' + address;
    if (disc != '') { 
    	html = html + '<br /><a href="/business/' + encodeURIComponent((name.toLowerCase())) + '" title="Visit Business homepage">Click to view the latest offers</a>';
    };
    GEvent.addListener(marker, 'click', function() {
        marker.openInfoWindowHtml(html);
    });
    GEvent.addListener(marker, 'hover', function() {
        marker.openInfoWindow(html);
    });
    return marker;
}

function createSidebarEntry(marker, name, address, postcode, cat, letter, distance, followed) {
    var div = document.createElement('li'); 

    var html = '<div class="vcard ' + ((letter == "A") ? 'noborder ' : '') + 'clearfix">';
        
    html = html + '<span class="marker">' + letter + '</span>';
    var n = (name.length > 25) ? name.substr(0,25) + "..." : name;
    html = html + '<div class="detail"><span class="hide">' + letter + '&nbsp;</span><span class="detail_top"><a href="/business/' + encodeURIComponent(name.toLowerCase()) + '?return=true" title="Visit Business homepage">' + n + '</a>';
    html = html + '<br /><em class="merc_cat">' + cat + ' &#183; ' + postcode + '</em></span>';
    var l = ($('location').get('value').length > 15) ? ($('location').get('value')).substr(0,15) + "..." : ($('location').get('value'));
    html = html + '<span class="detail_btm quiet">' + distance.toFixed(2) + ' miles from ' + l + '</span><span class="hide strong small"><br />Full address: ' + address + '</span>';
    html = html + '</div>';
    html = html + '<div class="action">';
    
    if (followed == "yes") {
    	html = html + '<img src="/assets/front/vcard_tick.gif" title="Following business" alt="Following business icon" />';
    } else if (followed == "no") {    	
    	html = html + '<a class="follow_merchant" href="/my_wedge/follow_business/' + encodeURIComponent((name.toLowerCase())) + '" title="Click to add to My Shops"><img src="/assets/front/vcard_add.gif" alt="Add business button" /></a>';
    } else {
        html = html + '<a href="/register_for_my_wedge" title="Click to add to My Shops"><img src="/assets/front/vcard_add.gif" alt="Add to My Shops button" /></a>'; 
    };
    
    html = html + '</div></div>';
    
    div.innerHTML = html;
    // div.style.cursor = 'pointer';
    //div.style.marginBottom = '5px';
    div.style.backgroundImage = "url('/assets/front/vcard_hover1.png')";
    div.style.backgroundPosition = "left top";
    div.style.backgroundRepeat = "repeat-x"; 
    if (postcode != '') { // only show Marker highlights for post coded buisness (NON ONLINE ONLY) 
	    GEvent.addDomListener(div, 'click', function() {
	          GEvent.trigger(marker, 'click');
	    });
	    GEvent.addDomListener(div, 'mouseover', function() {
	        GEvent.trigger(marker, 'hover'); //Highlight Marker on map on hover of left list item
	        div.style.backgroundImage = "url('/assets/front/vcard_hover1.png')";
	        div.style.backgroundPosition = "left bottom";
	        div.style.backgroundRepeat = "repeat-x"; 
	    });
	    GEvent.addDomListener(div, 'mouseout', function() {  
	        div.style.backgroundImage = "url('/assets/front/vcard_hover1.png')";
	        div.style.backgroundPosition = "left top";
	        div.style.backgroundRepeat = "repeat-x"; 
	    });
    }
    return div;
}

function doMapPaging(which) {
	$('start').set('value', which); // Set hidden field for Map paging
    //buildURL();
	searchLocations();
    return;
}

// **********************************************************************************************************************
// Global Functions
// **********************************************************************************************************************
Request.HTML.implement({

    processHTML: function(text){
        var match = text.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
        text = (match) ? match[1] : text;
           
        var container = new Element('div');
           
        return $try(function(){
        var root = '<root>' + text + '</root>', doc;
            doc = new DOMParser().parseFromString(root, 'text/html');
            root = doc.getElementsByTagName('root')[0];
            for (var i = 0, k = root.childNodes.length; i < k; i++){
                var child = Element.clone(root.childNodes[i], true, true);
                if (child) container.grab(child);
            }
            return container;
        }) || container.set('html', text);
    }

});

function slideShow (elms){
        // Version 0.2; Created by Kow, 2008; http://skyweb.hu/kow
        var pass = this;
        // initialise
        this.curImg = 0;
        this.slides = elms;
        this.slides.each(function(img, index){ 
            if(index > 0) img.fade(); 
            img.set('morph', { duration: 'long', transition: 'quint:in:out' });
        });
        this.next = function(){
            pass.curImg++;
            this.slides.each(function(img, index){ 
                img.morph({ opacity: 0 });
            }, this);
            if(pass.curImg == this.slides.length) pass.curImg = 0;
            this.slides[pass.curImg].morph({ opacity: 1 });
        }
};

function doMyWedgeLogin (form_id, submit_id, inject_id, where) { 
    //process My Wedge login form_id and inject the output msg "inside", "after" or "before" as stated by where in connection to div (inject_id)
    if ($(form_id)) {
        var response_status = new Element('div', { 'class': 'response_status' }).inject($(inject_id), where);
        var response_inner = new Element('div');
        var response_html = new Element('p', { 'class': 'bottom' });

        $(form_id).set('send', { 
            onSuccess: function(response){
                var msg = response.split('|');
                response_status.removeClass('loader_sml');
                response_inner.erase('class');   
                
                response_html.set('html',msg[1]).inject(response_inner,'inside');
                response_inner.addClass((msg[0] != 1) ? 'warning' : 'accepted').inject(response_status);
                if (msg[0] == 1) (function() { buildURL(); }).delay(1000);      
            }
        });
        
        $(form_id).addEvent('keydown', function(e) {
            if (e.key == 'enter') {
                e.stop();
                response_status.empty().addClass('loader_sml'); 
                $(form_id).send(); 
            }
        });
        
        $(submit_id).addEvent('click', function(e) {
            e.stop();
            response_status.empty().addClass('loader_sml'); 
            $(form_id).send(); 
        });
        
    }
};

function show_message (form_id, submit_id, inject_id, where, redirect_path) {  
    
    if (inject_id == null) inject_id = $(form_id);
    if (where == null) where = 'after';
    
	var response_status = new Element('div').addClass('response_status').inject($(inject_id), where);
    
	if (form_id == 'my_merchant_frm') tinyMCE.triggerSave();
	
    if ($(form_id)) {
	    $(form_id).set('send', { 
            onSuccess: function(response){	            
                var msg = response.split('|');
                response_status.removeClass('loader_sml');
	
                if (msg[0] == 2) {
            	    //go to page preview location
            	    window.location = msg[1];
                } else if (msg[0] == 3) {
            	    // AUTO SUBMIT hidden PAYPAL FORM
            	    if ($('paypal')) {
            		    new Element('p',{ html: msg[1], 'class': (msg[0] != 3) ? 'error' : 'success' }).inject(response_status);	
            		    (function() { $('paypal').submit() }).delay(3000);
            	    }
                } else if (msg[0] == 4) {
            	    // AUTO LOG INTO MY WEDGE
        		    new Element('p',{ html: msg[1], 'class': (msg[0] != 4) ? 'error' : 'success' }).inject(response_status);	
        		    (function() { window.location = redirect_path + "#welcome"; }).delay(3000);
                } else {
            	    //show message and redirect if save successful
            	    new Element('p',{ html: msg[1], 'class': (msg[0] != 1) ? 'error' : 'success' }).inject(response_status);	 
                    if (msg[0] == 1 && redirect_path != null) (function() { window.location = redirect_path; }).delay(2500);
                };
            }
        })
        
        if (submit_id == null) {
            var inputs = $(form_id).getElements('input');
            inputs.each(function(i) {
                if(i.getProperty('type') == 'submit') {
                    submit_id = i;
                };
            });
        };
        
        submit_id.addEvent('click', function(e) {
            e.stop();
            response_status.empty().addClass('loader_sml').highlight();
            /* IMPORTANT for TINYMCE : allows multiple textareas to be saved without being reset to blank */     
            if (form_id == "my_merchant_frm") tinyMCE.triggerSave(); 
            $(form_id).send(); 
        });
    };
};

function add_merchant (btn) {
    var href = btn.getProperty('href');
    
    btn.addEvent('click', function(e) {
        e.stop();
        var follow_req = new Request({
            url: href,
            onRequest: function(response) {
                shop_msg("notice", "Working...");
            },
            onComplete: function(response) {
                if ($defined(response)) {
                    var msg = response.split('|');

                    if (msg[0] == 1) {
                        new Element ('img', { src: '/assets/front/vcard_tick.gif', alt: 'Add to My Shops icon' }).replaces(btn);  
                        
                        var li = new Element ('li', { id: 'ms_' + msg[6], 'class': 'clearfix' });                  
                            var div = new Element ('div', { 'class': 'shop_wrapper clearfix' }).inject(li);                  
                                var logo = new Element ('div', { 'class': 'shop_logo' }).inject(div); 
                                    var img = new Element ('div', { 'class': 'img_frame' }).inject(logo); 
                                        new Element ('img', { src: '/merchant_uploads/' + msg[3], 'class': 'merc_img', alt: 'Photo for ' + msg[2] }).inject(img); 
                                                 
                                var details = new Element ('div', { 'class': 'shop_details' }).inject(div);   
                                    
                                    var remove_btn = new Element ('a', { 
                                        'class': 'shop_remove', href: msg[6], title: 'Remove this from My Shops' 
                                    }).addEvent('click', function(e) { 
                                        e.stop();  
                                        if(!confirm("Are you sure you want to remove this shop?")) {
                                            return; 
                                        };  
                                        remove_merchant(this); 
                                    }).inject(details);
                                                         
                                    var p = new Element ('p', { 'class': 'shop_title' }).inject(details);                  
                                        new Element ('a', { html: msg[2], href: '/business/' + msg[1], title: 'View business home for: ' + msg[2] }).inject(p);                  
                                    
                                    new Element ('p', { 'class': 'shop_desc small bottom', html: msg[4] }).inject(details);   
                                    new Element ('p', { 'class': 'small quiet bottom', html: 'added on ' + msg[5] }).inject(details);  
                                                                    
                                    new Element ('span', { 'class': 'hide', html: 'Remove this from My Shops' }).inject(remove_btn);                                 
                        
                        if($('my_shops_list') == null) { 
                            $('wpt_shops_body').empty();
                            var ul = new Element ('ul', { id: 'my_shops_list', 'class': 'clearfix' }).inject($('wpt_shops_body'));    
                        };
                        
                        li.inject($('my_shops_list'), "top");  
                        shop_msg("success", "Shop added!");
                    } else {
                        shop_msg("error", "Shop not added. Please try again later.");
                    };
                } else {
                    shop_msg("error", "Shop not added. Please try again later.");
                };
            }
        }).send();
                    
    });
};

function remove_merchant (btn) {   
        var ms_id = btn.getProperty('href'); 
        var follow_count = ($('my_shops_list').getChildren().length)-1;
        
        var remove_req = new Request({
            url: '/my_wedge/unfollow_business/' + ms_id,
            onRequest: function(response) {
                shop_msg("notice", "Working...");
            },
            onComplete: function(response) {  
                if ($defined(response)) {
                    var msg = response.split('|');

                    if (msg[0] == 1) {
                        $('ms_' + ms_id).dispose();
                            
                        if (follow_count == 0) {
                            $('my_shops_list').dispose();
                            new Element('h3',{ html: "No shops added yet?" }).inject($('wpt_shops_body'));
                            new Element('p',{ html: "To add a shop, click the <img src='/assets/front/vcard_add.gif' alt='Add to My Shops button' /> to follow them, or go to their business page and click 'Add to my shops'." }).inject($('wpt_shops_body'));
                        }
                        shop_msg("success", "Shop removed!");
                    } else {
                        shop_msg("error", "Not removed. Please try again later.");
                    };
                } else {
                    shop_msg("error", "Not removed. Please try again later.");
                };
            }
        }).send();
};

function shop_msg (type, msg) { 
    var div = new Element ('div', { 'class': 'shops_msg ' + type }).inject($('wprofile_tabs'), "bottom");
        var type_html = (type != "notice") ? "<strong>" + type.capitalize() + "</strong>: ": "";
        var html = new Element ('span', { html: type_html + msg }).inject(div); 
    var delay_time = (type == "error") ? 5000 : 1500;
    (function() { div.dispose(); }).delay(delay_time);       
};

function twitterCallback2(twitters) {
    var updates = []; 
    for (i=0; i<3; i++) {
        var username = twitters[i].user.screen_name;
        var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
            return '<a href="'+url+'">'+url+'</a>';
        }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
            return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
        });
        
        var li = new Element('li', { 'class': 'clearfix'});
        var span_icon = new Element('img', { src: '/assets/front/tweet.gif', alt: 'Tweet icon' }).inject(li);
        var span_tweet = new Element('span', { 'class': 'feed_updates_body clearfix' }).inject(li);
        var span_status = new Element('span', { html: status }).inject(span_tweet);
        var a_time = new Element('a', { href: 'http://twitter.com/'+username+'/statuses/'+twitters[i].id, 'class': 'twitter_time', html: relative_time(twitters[i].created_at) }).inject(span_tweet);
        updates.push(li);
    };                                          
    var updates_ul = new Element('ul', { 'class': 'feed_updates' }).adopt(updates).inject('feed_twitter_body');
};

function twitterCallbackBiz(twitters) {
    var updates = [];     
    for (i=0; i<twitters.length; i++) {
        var username = twitters[i].user.screen_name;
        var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
            return '<a href="'+url+'">'+url+'</a>';
        }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
            return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
        });
        
        var li = new Element('li', { 'class': 'clearfix'});
        var span_icon = new Element('img', { src: '/assets/front/tweet.gif', alt: 'Tweet icon' }).inject(li);
        var span_tweet = new Element('span', { 'class': 'merchant_twitter_body clearfix' }).inject(li);
        var span_status = new Element('span', { html: status }).inject(span_tweet);
        var a_time = new Element('a', { href: 'http://twitter.com/'+username+'/statuses/'+twitters[i].id, 'class': 'twitter_time', html: relative_time(twitters[i].created_at) }).inject(span_tweet);
        updates.push(li);
    };                                          
    var updates_ul = new Element('ul', { 'class': 'merchant_twitter' }).adopt(updates).inject('merchant_twitter_body');
};

function relative_time(time_value) {     
    var values = time_value.split(" ");
    time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
    var parsed_date = Date.parse(time_value);
    var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
    var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
    delta = delta + (relative_to.getTimezoneOffset() * 60);

    if (delta < 60) {
        return 'less than a minute ago';
    } else if(delta < 120) {
        return 'about a minute ago';
    } else if(delta < (60*60)) {
        return (parseInt(delta / 60)).toString() + ' minutes ago';
    } else if(delta < (120*60)) {
        return 'about an hour ago';
    } else if(delta < (24*60*60)) {
        return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
    } else if(delta < (48*60*60)) {
        return '1 day ago';
    } else {
        return (parseInt(delta / 86400)).toString() + ' days ago';
    };
};

function page_scroll(elm) {
    return new Fx.Scroll(document.body, {
        wait: false,
        duration: 'long',
        offset: {'x': 0, 'y': -50},
        transition: 'expo:in:out'
    }).toElement($(elm));
};

// **********************************************************************************************************************
// DOM READY EVENTS 
// **********************************************************************************************************************
window.addEvent('domready', function() {
    
    /***********************************************
    * Split path into array so pecific code is executed.        
    ************************************************/ 
    var path = window.location.pathname.split('/');
    var page = path[1];
    var sub_page = path[2];
    
    /***********************************************
    * Global functions              
    ************************************************/ 
    var search_func = (function() {
        if (($('location').get('value') != '') && ($('location').get('value') != 'street, area or postcode')) {
            if ($('start')) 
                $('start').set('value', '0');
                //(page == "my_wedge" && ($('keytags') && $('keytags') != '' && $('keytags') != 'undefined')) ? searchLocations() : buildURL();
                buildURL();
        } else {
            //empty Location with keywords will do AJAX search (without refresh)
            if (page == "my_wedge" && ($('keytags') && $('keytags').get('value') != '' && $('keytags').get('value') != 'undefined')) {
                searchLocations();
            } else {
                if ($('keytags') && $('keytags').get('value') != '' && $('keytags').get('value') != 'undefined')
                buildURL();
            }
            //(page == "my_wedge" && ($('keytags') && $('keytags') != '' && $('keytags') != 'undefined' && $('keytags') != 'eg: books')) ? searchLocations() : buildURL();
        };
    });
        
    $('search_button').addEvent('click', function(e) {
    	//check that both location/keytags are not both empty
        e.stop();
        search_func();
    }); 
    
    var help_panel = new Element('div', { id: 'help_panel', 'class': 'span-24 last', opacity: 0 });
    $('help_button').addEvent('click', function(e){
        e.stop();
        if($defined($('help_panel'))) {
            $('help_panel').dispose().setStyle('opacity', 0);
        } else {
            help_panel.inject($('find_wedge'), "after").fade('in');
        };
    });
    
    var findwedge_inputs = ['location', 'keytags']; // array of ids to reset on focus/blur
    findwedge_inputs.each (function(input_id) {
        if($defined($(input_id))) {
            var y = (input_id == 'keytags') ? '-12px' : '4px';
     
            if ($(input_id).getProperty('value') == "") 
                $(input_id).setStyle('background-position', '0px ' + y);

            $(input_id).addEvents({
                'focus': function (e) { 
                    this.setStyle('background-position', '0px -50px'); 
                },
                'blur': function (e) { 
                    if (this.getProperty('value') == "") {
                        this.setStyle('background-position', '0px ' + y); 
                    };
                },
                'keydown': function (e) {
                    if (e.key == 'enter') search_func();
                }
            }); 
        };
    }); 

    /***********************************************
    * Footer functions              
    ************************************************/ 
    
    // Newsletter signup on footer
    if ($defined($('newsletter_frm'))) 
        show_message('newsletter_frm', null, null, null, null);
    
    // Business Login
    if ($defined($('merchant_login_frm'))) {
        if ($('merchant_pwd')) { 
            // login  
            show_message('merchant_login_frm', null, 'merchant_login', null, "/business");
            // ps_reminder
            show_message('merchant_pr_frm', null, null, 'bottom', "/Home");
        };
        
        // Handle password reminder link on footer business login 
    	$('pwd_reminder').addEvent('click', function(e) {
            e.stop();
            var text = $('pwd_reminder').get('html') == 'Hide' ? 'Get your password?' : 'Hide';
            $('pwd_reminder').set('html', text);
            $('merchant_pr_frm').toggleClass('hide');
        });
    };
    
    // My Wedge Login        
    if ($defined($('my_wedge_login_frm'))) {
        if ($defined($('login_button'))) { 
            doMyWedgeLogin('my_wedge_login_frm', 'login_button', 'my_wedge', "after");
            // ps_reminder
            show_message('mw_pr_frm', null, 'mw_pr_frm', 'bottom', "/my_wedge");
        };
        
        // Handle password reminder link on footer business login 
        $('mw_pwd_reminder').addEvent('click', function(e) {
            e.stop();
            var text = $('mw_pwd_reminder').get('html') == 'Hide' ? 'Forgotten password?' : 'Hide';
            $('mw_pwd_reminder').set('html', text);
            $('mw_pr_frm').toggleClass('hide');
        });
    };
    
    // Prepare tab for feed in footer
    if ($defined($('feed_btns'))) {
	    var f_btns = $('feed_btns').getElements('a');  
	    var f_body = $('feed_body').getChildren();  
	    
	    f_btns.each (function(f_btn) {
	        f_btn.addEvent('click', function(e) {
	            e.stop();
	            f_btns.each (function(f_bt) {
	                (f_bt.getProperty('id') != f_btn.getProperty('id'))     
	                    ? f_bt.removeClass('feed_btn_on')                    
	                    : f_bt.addClass('feed_btn_on');
	            });
	            f_body.each (function(f_b) {
	                (f_b.getProperty('id') == f_btn.getProperty('href'))     
	                    ? f_b.removeClass('hide')                    
	                    : f_b.addClass('hide');
	            });                                    
	        });
	    });
    };
    
    var load_twitter = new Asset.javascript('http://twitter.com/statuses/user_timeline/wedgecard.json?callback=twitterCallback2');
    
    /***********************************************
    * Page specific functions 
    ************************************************/ 
    switch(page) {                                 
        case 'Home':
        
            // Setup & display slideshow 
            var loader = new Fx.Morph($('s_images_loader'), { duration: 'normal', link: 'chain', transition: 'quint:in:out' });                  
            var img_array = new Array();
            for (var i = 0; i < 5; i++) {
                img_array.push("./images/merchant_0" + (i + 1) + ".jpg");
            };
            img_array.push("./images/RBKC_banner.jpg");
            
            var home_images = new Asset.images(img_array, {
                onProgress: function(counter,index) {
                    $('s_images_counter').set('html', "Loading image " + (counter + 1) + " of " + img_array.length);
                },
                onComplete: function(){ 
                    $('s_images_loader').fade('out').dispose();                                 
                    $('s_images_holder').dispose(); 
                    
                    home_images.each (function(image) {
                        var new_image = image;  
                        var src = image.getProperty('src');  
                        if (src.test("RBKC") || src.test("03")) new_image = new Element ('a', { href: '/News/?n=207', title: 'Big News! Wedge - coming to the Royal Borough of Kensington and Chelsea' }).grab(image);
                        new_image.inject($('s_images'), "top");      
                    });
                }
            });
            
            var ss = new slideShow(home_images);
            ss.next.periodical(5500, ss); 
            
            break; 
    	case 'my_wedge':  
        
            var w_modal = new wedge_modal({ container: $(document.body) });

            if($defined($('myshops_help'))) {
                $('myshops_help').addEvent('click', function(e) {
                    e.stop(); 
                    w_modal.open('help');
                }); 
            };
            
            if($defined($('myshops_print'))) { 
                $('myshops_print').addEvent('click', function(e) {
                    e.stop(); 
                    if ($('shop_count').get('html') > 0) {
                        window.open(this.getProperty('href'), '', 'width=643, scrollbars=yes, resizable=yes');                                                                         
                    } else {
                        alert('You must be following at least one shop to print.\nTo add to My Shops, click the green + to follow them,\nor go to their business page and click \'Add to my shops\'.');
                    };
                }); 
            };   
            
            $$('.wmap_loc').addEvent('click', function(e) { //Handle My places/locations button clicks
                e.stop();
                myLocation(this.getProperty('href'));
                ($('category').set('value', '0')); // reset category drop down
                buildURL();
            });

            $$('a.shop_remove').each (function(btn, index) {
                btn.addEvent('click', function(e) {
                    e.stop(); 
                    if(!confirm("Are you sure you want to remove this shop?")) {
                        return; 
                    };
                    remove_merchant(btn);
                });
            });
            
            break;
        case 'business':
        
        	if ($defined($('voucher_pop_up'))) {
	            $('voucher_pop_up').addEvent('click', function(e) { 
	                e.stop();
	                window.open(this.getProperty('href'), '', 'width=375, height=269, scrollbars=no, resizable=no');                                                     
	            });
        	};    
    
            if ($defined($('my_merchant_frm'))) {
                myCal1 = new Calendar({ merchant_discount1_start_date: 'Y-m-d' }, { tweak: { x: 6, y: 0 }});
                myCal2 = new Calendar({ merchant_discount1_expiry_date: 'Y-m-d' }, { tweak: { x: 6, y: 0 }});
                myCal3 = new Calendar({ merchant_discount2_start_date: 'Y-m-d' }, { tweak: { x: 6, y: 0 }});
                myCal4 = new Calendar({ merchant_discount2_expiry_date: 'Y-m-d' }, { tweak: { x: 6, y: 0 }});
                myCal5 = new Calendar({ merchant_discount3_start_date: 'Y-m-d' }, { tweak: { x: 6, y: 0 }});
                myCal6 = new Calendar({ merchant_discount3_expiry_date: 'Y-m-d' }, { tweak: { x: 6, y: 0 }});
                myCal7 = new Calendar({ merchant_voucher_start_date: 'Y-m-d' }, { tweak: { x: 6, y: 0 }});
                myCal8 = new Calendar({ merchant_voucher_expiry_date: 'Y-m-d' }, { tweak: { x: 6, y: 0 }});

                if (sub_page == 'new') {
                    var redirect_path = "/business/" + encodeURIComponent(($('merchant_name').value).toLowerCase());
                    show_message('my_merchant_frm', null, null, null, redirect_path);               
                };
            };
            
            break; 
        default:  
            
            // Get card / My Wedge registration form
            if ($defined($('get_card_diagram'))) {
                $$('#get_card_diagram a').each (function(a) {
                    a.addEvent('click', function(e) {
                        e.stop();
                        var which = a.getProperty('href');
                        if ($('mp_head')) $('mp_head').dispose(); 
                        var form_head = new Element('div', { id: 'mp_head' }); 
                                        new Element('h3', { html: a.getProperty('title') }).inject(form_head); 
                            form_head.inject($('my_profile'), "top").highlight();
                            
                        $('which_frm').value = which;
                        switch (which) {
                        	case 'buy':
                        		$('submit').value = " Save my details and send me to PayPal! ";
                        		break;
                        	case 'request':
                        		$('submit').value = " Send me a card and take me to My Wedge! ";
                        		break;
                        	default:
                        		$('submit').value = " Save my details and take me to My Wedge! ";
                        		break;
                        }

                        $('my_profile').removeClass('hide');
                        page_scroll('my_profile');
                    });
                });
            };  

            if ($defined($('my_profile'))) {
            	if ($('mp_tab_wrapper')) {
                    var mp_tabs = $('mp_tab_wrapper').getElements('a');  
                    var mp_buts = $('my_profile_frm').getElements('a.mp_but');  
                    var nav_buts = mp_tabs.combine(mp_buts);
	                var mp_frames = $('my_profile_frm').getElements('fieldset');  
                    
                    var show_hide = (function(view) {  
                            
                            mp_tabs.each (function(tab) {
                                (tab.getProperty('href') != view)     
                                    ? tab.removeClass('mp_tab_on')                    
                                    : tab.addClass('mp_tab_on');
                            });
                            mp_frames.each (function(frame) {
                                (frame.getProperty('id') == view + "_body")     
                                    ? frame.removeClass('hide')                    
                                    : frame.addClass('hide');
                            });
                    });
                    
                    nav_buts.each (function(nb) {
                        nb.addEvent('click', function(e) {
                            e.stop();
                            //var view = this.getProperty('href'); 
                            show_hide(this.getProperty('href'));
                        });
                    });
                    
                    var hash = window.location.hash;
                    if($defined(hash) && hash.contains('options')) 
                        show_hide('options');
            	};
            };  

            // Ccreate Wedge Team Accordion instance
            if ($defined($('team_gallery'))) {
                var wedge_team = new Accordion($('wedge_team'), $$('.zoosh'), $$('.bio'), {
                    opacity: true,
                    alwaysHide: true,
                    display: 0,
                    duration: 250
                });
            };
            
            // Partner registration form (Liezel) submission
            if ($defined($('partner_frm'))) 
    	        show_message('partner_frm', null, null, null, "/partner_registration");
            
            if ($defined($('my_profile_frm'))) 
                show_message('my_profile_frm', null, null, null, "/my_wedge");
            
            break;
    };
    
// **********************************************************************************************************************
// END DOM READY
// **********************************************************************************************************************
});