/**
 * @author Dave
 */
var $my = {
    "openID": "",
    "siteId": "04361592778514215361",
    "ajaxAPI": "ABQIAAAAGC8G7OF6J5v9dWczdmw1KBR9wPGn3vcdGzbBn2gf43tk_5DNohTosgv_FkKo4jRhpS321NybRtgjtQ",
    "allExpanded": false,
    "leedsSocial": false,
    "loadGoogle": true,
    "map": {
        "id": "",
        "geoLong": "",
        "geoLat": ""
    },
	"currentVersion": "2.5"
};

function setCookie( name, value, expires, path, domain, secure ) {

    var today = new Date();
    today.setTime( today.getTime() );
    
    if ( expires ) {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    
    var expires_date = new Date( today.getTime() + (expires) );
    
    document.cookie = name + "=" +escape( value ) +
    ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
    ( ( path ) ? ";path=" + path : "" ) +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );  
}

function updateWindowHash(){
}

function setExpanded() {
    if ($my.openID > '' ) {
        var $oldId = $("#gig" + $my.openID);
        $oldId.find(".ui-icon-circle-minus").removeClass("ui-icon-circle-minus").addClass("ui-icon-circle-plus");
        $oldId.removeClass('gig-information-show');
    }
    $(".gig-venue-information").hide();
    $(".gig-information").show();
    $my.allExpanded = true;
}

function setHeadliner() {
    if ($my.openID > '' ) {
        var $oldId = $("#gig" + $my.openID);
        $oldId.find(".ui-icon-circle-minus").removeClass("ui-icon-circle-minus").addClass("ui-icon-circle-plus");
        $oldId.removeClass('gig-information-show');
    }
    $(".gig-information").hide();
    $(".gig-venue-information").show();
    $my.allExpanded = false;
}

String.prototype.capitalize = function(){ 
    return this.replace(/\w+/g, function(a){
        return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
    });
};

function hideOldGig() {
    var $oldId = $("#gig" + $my.openID);
    $oldId.find(".ui-icon-circle-minus").removeClass("ui-icon-circle-minus").addClass("ui-icon-circle-plus");
    $oldId.find(".googleMap").hide("slow");
    if ($oldId.find(".gig-information").is(":visible")) {
        if ( $my.allExpanded ) {
            $oldId.find(".gig-venue-information").hide("slow");        
        } else {
            $oldId.find(".gig-information").hide("slow");        
        }
    } else {
        if ( $my.allExpanded ) {
            $oldId.find(".gig-venue-information").hide("slow");        
            $oldId.find(".gig-venue-information").css("display", "none");
        } else {
            $oldId.find(".gig-information").css("display", "none");
        }
    }
    $oldId.removeClass('gig-information-show');
}

function showGig(id, showGigsParm){

    if ($my.openID > '' && $my.openID !== showGigsParm + id) {
        hideOldGig();
    }
    var $gig = $("#gig" + showGigsParm + id);
    var $gigInformation = $gig.find(".gig-information");
    var $gigIconPlus = $gig.find(".ui-icon-circle-plus");
    var $gigVenueInformation = $gigInformation.find(".gig-venue-information");

    var hide;
    
    if ($gigIconPlus.length > 0) { // Display Information
        hide = false;
        currGig = showGigsParm + id;
        $gigIconPlus.removeClass("ui-icon-circle-plus").addClass("ui-icon-circle-minus");
        $gig.addClass('gig-information-show');
        $gigVenueInformation.html('<div class="loading"><p>Gig Information Loading...</p></div>');
        var vars = {
            "id": id
        }
        $.getJSON("json/gig.js", vars, function(gig){
            var venueInformation = '';
            var ticketsDialog = '';
            try {
                if (gig.tickets.price.length > 0) {
                    venueInformation += '<div class="gigTickets">Ticket price: &pound;' + gig.tickets.price;
                    if (gig.tickets.links.length > 0) {
                        venueInformation += ' [<a href="#" onclick="return showTickets();">tickets available</a>]';
                        ticketsDialog += '<p>Tickets for this gig are currently on sale at the following shops:</p>';
                        ticketsDialog += '<ul class="links">';
                        $.each(gig.tickets.links, function(j, link){
                            ticketsDialog += '<li><a href="' + link.url + '" target="_new">' + link.name + '</a></li>';
                        });
                        ticketsDialog += '</ul>';
                        ticketsDialog += '<p>Price excludes P&P and fees.</p>';
                        $my.ticketsDialog.html(ticketsDialog);
                    }
                    venueInformation += '</div>';
                }
            } 
            catch (err) {
            }
            venueInformation += '<div id="map' + showGigsParm + id + '" class="googleMap"></div>';
            try {
                $.each(gig.venue.address, function(j, addrLine){
                    venueInformation += '<div class="venueAddrLine">' + addrLine + '</div>';
                });
                if (gig.venue.telephone.length > 0) {
                    venueInformation += '<div class="venueTelephone">' + gig.venue.telephone + '</div>';
                }
                if (gig.venue.website.length > 0) {
                    venueInformation += '<div class="venueWebsite"><a href="http://' + gig.venue.website + '">' + gig.venue.website + '</a></div>';
                }
            } 
            catch (err) {
            }
            if (gig.preview.length > 0) {
                venueInformation += '<div class="gigPreview"><strong>Submitted Preview:</strong><br><br>' + gig.preview + '</div>';
            }
            if ( $my.leedsSocial ) {
                venueInformation += '<div class="socialOptions ui-state-default ui-corner-all"><div class="links"><strong>Leeds Social</strong>: <a href="#" onclick="return showAttendance(' + id + ', \'' + delquote(gig.bands[0]) + ' @ ' + delquote(gig.venue.name) + '\', \'' + delquote(gig.dateText) + '\');">See Who\'s Going</a> | <a href="#" onclick="return showTalk(' + id + ', \'' + delquote(gig.bands[0]) + '\');">Talk About This Gig</a></div></div>';            
            }
            
            venueInformation += '<div class="permaLink links">Permanent Event Link: <a href="/event-' + id + '.html">www.leedsgigs.co.uk/event-' + id + '.html</a></div>';
            
            $gigVenueInformation.html(venueInformation);

            try {
                showMap(showGigsParm + id, gig.venue.geo.longitude, gig.venue.geo.latitude);
            } 
            catch (err) {
            }
        });
        $my.openID = showGigsParm + id;

        try {
            pageTracker._trackPageview('showGig?id='+id+'&showGigsParm='+showGigsParm);
        } catch(err) {}
    
    } else { // Hide Information
        hide = true;
        currGig = '';
        $gig.find(".ui-icon-circle-minus").removeClass("ui-icon-circle-minus").addClass("ui-icon-circle-plus");
        $gig.removeClass('gig-information-show');
        $my.openID = '';
    }

    if ( hide ) {
        $gig.find(".googleMap").hide("slow");
        if ( $my.allExpanded ) {
            $gigVenueInformation.hide("slow");        
        } else {
            $gigInformation.hide("slow");        
        }
    } else {
        if ( $my.allExpanded ) {
            $gigVenueInformation.show("slow");        
        } else {
            $gigInformation.show("slow");        
        }
    }
    
    return false;
}

function formatGig(event, showGigsParm){
    var eventHTML = '';
    eventHTML += '<div id="gig' + showGigsParm + event.id + '" class="gig-item links">';
    eventHTML += '<a href="/event-' + event.id + '.html" onclick="return showGig(' + event.id + ', \'' + showGigsParm + '\');"><span class="ui-icon ui-icon-circle-plus" style="float:right;">Info</span></a>';
    eventHTML += '<span class="gig-venue">' + event.venue + '</span>';
    if ( showGigsParm == 'sr') {
        eventHTML += ' ['+event.dateText+']';
    }
    eventHTML += ': <span class="gig-headliner">' + event.bands[0] + '</span>';
    eventHTML += '<div class="gig-information">';
    eventHTML += '<span class="fullLineUp">';
    eventHTML += 'Full Line Up: <a href="#" class="band">' + event.bands[0] + '</a>';
    $.each(event.bands, function(j, band){
        if (j > 0) {
            eventHTML += ' + <a href="#" class="band">' + band + '</a>';
        };
            });
    eventHTML += '</span>';
    eventHTML += '<div class="gig-venue-information"></div>';
    eventHTML += '</div></div>';
    return eventHTML;
}

function mapsLoaded() {
    try {
        if (GBrowserIsCompatible()) {
			var pt = new GLatLng($my.map.geoLat, $my.map.geoLong);
            var map = new GMap2(document.getElementById("map" + $my.map.id));
            map.addControl(new GSmallMapControl());
            map.setCenter(pt, 15);
            map.addOverlay(new GMarker(pt));
			map.resizeMap();
        }
    } 
    catch (err) {
    }
}
function showMap(id, geoLong, geoLat){

    $my.map.id = id;
    $my.map.geoLong = geoLong;
    $my.map.geoLat = geoLat;

    google.load("maps", "2", {"callback" : mapsLoaded});
}

function displayAds(){
    $(".a468x60:hidden").html('');
    $(".a468x60:visible").html('<iframe src="advert.php" style="border:0;margin:0 auto;padding:0;width:468px;height:60px;" frameborder="0" scrolling="no"></iframe>');
}

function showTickets(){
    $my.ticketsDialog.dialog('open');
    try {
        pageTracker._trackPageview('showTickets');
    } catch(err) {}
    return false;
}

function delquote(str){
    return (str = str.replace(/["']{1}/gi, ""));
}

function getBandLinks(mbid, bandName) {
    var vars = {
        "mbid": mbid,
        "parms": "url-rels"
    }
    $.getJSON('json/musicBrainz.js', vars, function(musicBrainz){
        var count = 0;
        $.each(musicBrainz.relation, function(i, relation) {
            if ( i == 0 ) {
                $("#"+mbid).append('<p style="margin-top:1em"><strong>Related Links for '+bandName+':</strong></p><ul>');
            }
            $("#"+mbid).append('<li class="links"><a href="'+ relation.url + '">'+relation.label+'</a></li>');
            count++;
        });
        if (count > 0) {
            $("#"+mbid).append('</ul>');
        }
    });  
}

function bandSearch(bandName) {
    if ($my.tabSearch.length == 0) {
        $my.allTabs.tabs('add', '#tab-search', 'Band Info');
        $my.tabSearch = $("#tab-search");
    }
    $my.tabSearch.html('<div class="loading"><p>Band Information Loading...</p></div>');
    $my.allTabs.tabs('select', '#tab-search');
    if ( window.screenTop !== 0) {
        window.scrollTo(window.screenLeft, 0);        
    }
    var vars = {
        "bandName": escape(bandName)
    }
    $.getJSON("json/band.js", vars, function(band){
       
        var gigsHTML = '<div class="gigs"><div class="a468x60"></div><div class="band-heading"><p>'+band.bandName+'</p></div></div>';
        if ( band.events.length > 0) {
            gigsHTML += '<p>'+band.bandName+' will be playing at the following Leeds gigs:</p>';
            $.each(band.events, function(i, event){
                gigsHTML += formatGig(event, 'sr');
            });
        } else {
            gigsHTML += '<p>We have not found any Leeds gigs for '+band.bandName+'.</p>';
        }

        if ( band.biography > '') {
            gigsHTML += '<div class="bandBio"><strong>Band Biography for '+band.bandName+':</strong>';
            gigsHTML += '<br><br>';
            gigsHTML += '<img src="'+band.image+'" style="float:right;vertical-align:top;margin:0 0 1em 2em;">';
            gigsHTML += band.biography;
            if ( band.mbid > '') {
                gigsHTML += '<div class="bandLinks" id="'+band.mbid+'"></div>';
            } 
            gigsHTML += '<div class="break"></div>';
            gigsHTML += '</div>';
            gigsHTML += '<a href="'+band.lastfmurl+'"><img src="images/badge_red.gif" style="margin:1em 0"></a>';
        }
       
        gigsHTML += '<div class="permaLink links">Permanent Band Link: <a href="/band-' + bandName.toLowerCase().replace(/\s/g, "-") + '.html">www.leedsgigs.co.uk/band-' + bandName.toLowerCase().replace(/\s/g, "-") + '.html</a></div>';

        $my.tabSearch.html(gigsHTML);

        if ( band.mbid > '') {
            getBandLinks(band.mbid, band.bandName);
        }
        
        if ($my.allExpanded) {
            setExpanded();
        }
        try {
            pageTracker._trackPageview('showBand?name='+band.bandName);
        } catch(err) {}
        $(".band").click(attachBandClick);
        displayAds();
    });
    return false;
}

function attachBandClick(){
    var bandName = $(this).html();
    bandSearch(bandName);
    return false;
};

function search(){
    var bandName = $("#bandSearch").val();
    bandSearch(bandName.capitalize());
    return false;
};

function showAttendance(id, title, description){
    $("#div-1139312149532651411").html('');
    $my.attendanceDialog.dialog('open');
    google.friendconnect.container.setParentUrl('/' /* location of rpc_relay.html and canvas.html */);
    google.friendconnect.container.renderOpenSocialGadget({
        id: 'div-1139312149532651411',
        url: 'http://www.google.com/ig/modules/socialevent.xml',
        site: $my.siteId,
        'view-params': {
            "id": id,
            "title": title,
            "description": description,
            "scope": "ID"
        }
    });
    try {
        pageTracker._trackPageview('showAttendance?id='+id+'&title='+title);
    } catch(err) {}
    return false;
}

function showTalk(id, title){
    $("#div-3037094006020734376").html('');
    $("#ui-dialog-title-talkDialog").html('Gig Talk - ' + title);
    $my.talkDialog.dialog('open');
    var skin = {};
    skin['BORDER_COLOR'] = '#222222';
    skin['ENDCAP_BG_COLOR'] = '#222222';
    skin['ENDCAP_TEXT_COLOR'] = '#ffffff';
    skin['ENDCAP_LINK_COLOR'] = '#F6992D';
    skin['ALTERNATE_BG_COLOR'] = '#222222';
    skin['CONTENT_BG_COLOR'] = '#222222';
    skin['CONTENT_LINK_COLOR'] = '#F6992D';
    skin['CONTENT_TEXT_COLOR'] = '#ffffff';
    skin['CONTENT_SECONDARY_LINK_COLOR'] = '#F6992D';
    skin['CONTENT_SECONDARY_TEXT_COLOR'] = '#ffffff';
    skin['CONTENT_HEADLINE_COLOR'] = '#ffffff';
    skin['DEFAULT_COMMENT_TEXT'] = '- add your comment here -';
    skin['HEADER_TEXT'] = 'Comments';
    skin['POSTS_PER_PAGE'] = '10';
    google.friendconnect.container.setParentUrl('/' /* location of rpc_relay.html and canvas.html */);
    google.friendconnect.container.renderWallGadget({
        id: 'div-3037094006020734376',
        site: $my.siteId,
        'view-params': {
            "disableMinMax": "true",
            "scope": "ID",
            "features": "video,comment",
            "docId": id,
            "startMaximized": "true"
        }
    }, skin);
    try {
        pageTracker._trackPageview('showTalk?id='+id+'&title='+title);
    } catch(err) {}
    return false;
}

$(document).ready(function(){

    $("#initialFlash").hide();
    $(".advert").show();

    $(".viagogo_feeds_widget a").each(function(i){
        var href = $(this).attr('href');
        $(this).attr('href', href+'?affiliateID=520&PCID=AFFIAFFUKLeeds78867');
    });

    $my.tabSearch = $("#tab-search");

    if ( $my.loadGoogle ) {
        var script = document.createElement("script");
        script.src = "http://www.google.com/jsapi?key="+$my.ajaxAPI;
        script.type = "text/javascript";
        document.getElementsByTagName("head")[0].appendChild(script);        
    }
                                 
});

