var connectorGlobalDirectoryMap;
var ConnectorDirectory = new Class({

    favoriteLinksList: false,
    vcardClone: false,
    vcardCloneQ: false,
    geo: false,
    directionsContainer: false,
    mapContainer: false,
    directions: false,
    map: false,
    marker: false,

    initialize: function( ) {
        var favoriteLinksList = [];
        // get all favorite links
        var favoriteLinks = $$('a.changeFavoritesButton');
        if( favoriteLinks.length > 0 ){
            for( var i = 0; i < favoriteLinks.length; i++ ){
                var favoriteLink = favoriteLinks[i];
                if( !favoriteLinksList.contains( favoriteLink.id.toString() ) ){
                    favoriteLinksList.include( favoriteLink.id.toString() );
                    favoriteLink.addEvent( 'click', this.favoriteButtonClick.bind( this ) );
                }
            } // end for
        }

        var featureLinksList = [];
        // get all feature links
        var featureLinks = $$('a.feature-button');
        if( featureLinks.length > 0 ){
            for( var i = 0; i < featureLinks.length; i++ ){
                var featureLink = featureLinks[i];
                if( !featureLinksList.contains( featureLink.id.toString() ) ){
                    featureLinksList.include( featureLink.id.toString() );
                    featureLink.addEvent( 'click', this.featureButtonClick.bind( this ) );
                }
            } // end for
        }

        //activate-listing-button
        var activateLinksList = [];
        // get all feature links
        var activateLinks = $$('a.activate-listing-button');
        if( activateLinks.length > 0 ){
            for( var i = 0; i < activateLinks.length; i++ ){
                var activateLink = activateLinks[i];
                if( !activateLinksList.contains( activateLink.id.toString() ) ){
                    activateLinksList.include( activateLink.id.toString() );
                    activateLink.addEvent( 'click', this.activateButtonClick.bind( this ) );
                }
            } // end for
        }


        //activate-listing-button
        var printLinksList = [];
        var printLinks = $$('a.print');
        if( printLinks.length > 0 ){
            for( var i = 0; i < printLinks.length; i++ ){
                var printLink = printLinks[i];
                if( !printLinksList.contains( printLink.id.toString() ) ){
                    printLinksList.include( printLink.id.toString() );
                    printLink.addEvent( 'click', this.printButtonClick.bind( this ) );
                }
            } // end for
        }

    },

    printButtonClick:function( event ){
        new Event( event ).stop();
        
        this.map = connectorGlobalDirectoryMap;

        var vcard = $$( '.vcard' );
        if( vcard.length > 0 ){
            vcard = vcard[0];
            var vcardClone = vcard.clone();
            /** clear useless data **/
            var vcardbusinessControlsContainer = vcardClone.getElementsBySelector( '.businessControlsContainer' );
            if( vcardbusinessControlsContainer.length > 0 ){
                vcardbusinessControlsContainer[0].remove();
            }
            var otherLocationContainer = vcardClone.getElementsBySelector( '.otherLocationContainer' );
            if( otherLocationContainer.length > 0 ){
                otherLocationContainer[0].remove();
            }
            var geoLocationLinks = vcardClone.getElementsBySelector( 'a.geoLocationLink' );
            if( geoLocationLinks.length > 0 ){
                for( var i = 0; i < geoLocationLinks.length; i++ ){
                    geoLocationLinks[i].remove();
                } // end for
            }

            var mapContainer, directionsContainer;
            var divs = vcardClone.getElements( 'div' );
            for( var t = 0; t < divs.length; t++ ){
                if( divs[t].id == 'mapResults' ){
                    this.directionsContainer = divs[t];
                }
                if( divs[t].id == 'map' ){
                    mapContainer = divs[t];
                }
            }

            var businessLocations = vcardClone.getElementsBySelector( '.geo' );
            if( businessLocations.length > 0 ){
                // get latitude
                var lat = businessLocations[0].getElementsBySelector( '.latitude' );
                lat = lat[0].innerHTML;
                // get longitude
                var lng = businessLocations[0].getElementsBySelector( '.longitude' );
                lng = lng[0].innerHTML;
                this.geo = { 'latitude':Number( lat ), 'longitude':Number( lng ) };
            }
            
            var cl_directions_form = vcardClone.getElements( 'form' )[0];
            if( cl_directions_form ){
                var inputs = vcardClone.getElements( 'input' );
                for( var c = 0; c < inputs.length; c++ ){
                    if( inputs[c].id == 'cl_q_location' ){
                        this.vcardCloneQ = inputs[c];
                    }
                }
                cl_directions_form.addEvent( 'submit', this.getDirectionsSubmit.bind(this) );
            }

            // hide site
            $('container4').style.display = 'none';
            $('fine_print').style.display = 'none';
            // build print page
            var connectorPrintContainer = new Element('div',{'id':'connectorPrintContainer'});
            var connectorPrintWrapper = new Element('div',{'class':'connectorPrintWrapper'});
            var header = new Element('div',{'class':'connectorPrintHeader'});
            var span = new Element('span').setText(' Business Directory');
            var headone = new Element('h1').setText('ConnectorLocal.com');
            span.injectInside( headone );
            headone.injectInside( header );
            var closeButton = new Element('a',{'href':'#','class':'printCloseButton'}).setText('close');
            var printButton = new Element('a',{'href':'#','class':'printButton'}).setText('print');
            printButton.addEvent( 'click', this.pagePrint.bind(this) );
            closeButton.addEvent( 'click', this.closePrint.bind(this) );
            new Element('div',{'class':'connectorLocalLink'}).setText('http://www.connectorlocal.com/directory').injectInside( header );
            closeButton.injectInside( header );
            printButton.injectInside( header );
            header.injectInside( connectorPrintWrapper );
            var connectorPrintContentContainer = new Element('div',{'class':'connectorPrintContentContainer'});
            vcardClone.injectInside( connectorPrintContentContainer );
            connectorPrintContentContainer.injectInside( connectorPrintWrapper );
            connectorPrintWrapper.injectInside( connectorPrintContainer );
            document.body.appendChild( connectorPrintContainer );
        }

    },

    setupIcon:function(colorName) {
        var icon = new GIcon();
        icon.image = "http://labs.google.com/ridefinder/images/mm_20_" + colorName + ".png";
        icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
        icon.iconSize = new GSize(12, 20);
        icon.shadowSize = new GSize(22, 20);
        icon.iconAnchor = new GPoint(6, 20);
        icon.infoWindowAnchor = new GPoint(5, 1);
        return icon;
    },

    initMap:function( lat, lng ){
        if (GBrowserIsCompatible()) {
            this.map = new GMap2( this.mapContainer );
            this.map.setCenter( new GLatLng( lat, lng ), 14 );
        } else{
            alert('Your browser is not compatible with Google Maps.');
        } // end if
    },

    getDirectionsSubmit:function( event ){
        new Event( event ).stop();
        var lat,lng;

        var location = false;
        if( this.vcardCloneQ ){
            if( this.vcardCloneQ.value.length > 3 ){
                location = this.vcardCloneQ.value;
            }
        }
        if( !location ){
            return null;
        }
        lat = this.geo.latitude;
        lng = this.geo.longitude;
        if( this.directions ) this.directions.clear();
        this.directions = new GDirections( this.map, this.directionsContainer );
        var dirData = location + " to " + lat + "/" + lng;
        this.directions.load(dirData);
    },

    pagePrint:function( event ){
        new Event( event ).stop();
        window.print();
    },

    closePrint:function( event ){
        new Event( event ).stop();
        if( $('connectorPrintContainer') ){
            document.body.removeChild( $('connectorPrintContainer') );
        }
        // hide site
        $('container4').style.display = '';
        $('fine_print').style.display = '';
    },

    activateButtonClick:function( event ){
        new Event( event ).stop();
        var target = event.target || event.srcElement;
        var active_listing_id = target.id;
        // make sure we have the right id
        if( active_listing_id.test('hide_listing_') ){
            active_listing_id = Number( active_listing_id.substring(13).toInt() );
            // city id was found
            this.changeActive( active_listing_id );
        }
    },

    featureButtonClick:function( event ){
        new Event( event ).stop();
        var target = event.target || event.srcElement;
        var feature_listing_id = target.id;
        // make sure we have the right id
        if( feature_listing_id.test('feature_listing_') ){
            feature_listing_id = Number( feature_listing_id.substring(16).toInt() );
            // city id was found
            this.changeFeature( feature_listing_id );
        }
    },

    changeActive:function( listing_id ){
        // show the loading icon
        var loaderImg = '<h5>Please wait while we process your request.</h5><img src="/images/ajax-loader.gif" height="19" width="220" />';

        if( $( 'business_listing_' + listing_id ) ){
            var loadingContainer = new Element('div', {'id': 'loader_'+ listing_id, 'class': 'loadingContainer'}).injectInside( $( 'business_listing_' + listing_id ) );
            loadingContainer.innerHTML = loaderImg;
        }

        new Ajax("/directory/js/functions/changeActive.php",{
            method:'get',
            data:'listing_id=' + listing_id ,
            onComplete:this.changeActiveResponse.bind(this),
            onFailure:function( response ){ this.showActiveChangeError.bind( this ); }
        }).request();
    },

    changeFeature:function( listing_id ){

        // show the loading icon
        var loaderImg = '<h5>Please wait while we process your request.</h5><img src="/images/ajax-loader.gif" height="19" width="220" />';

        if( $( 'business_listing_' + listing_id ) ){
            var loadingContainer = new Element('div', {'id': 'loader_'+ listing_id, 'class': 'loadingContainer'}).injectInside( $( 'business_listing_' + listing_id ) );
            loadingContainer.innerHTML = loaderImg;
        }

        new Ajax("/directory/js/functions/changeFeature.php",{
            method:'get',
            data:'listing_id=' + listing_id ,
            onComplete:this.changeFeatureResponse.bind(this),
            onFailure:function( response ){ this.showFeatureChangeError.bind( this ); }
        }).request();
    },

    favoriteButtonClick:function( event ){
        new Event( event ).stop();
        var target = event.target || event.srcElement;
        var favorite_listing_id = target.id;
        // make sure we have the right id
        if( favorite_listing_id.test('favorite_listing_') ){
            favorite_listing_id = Number( favorite_listing_id.substring(17).toInt() );
            // city id was found
            this.changeFavorite( favorite_listing_id );
        }
    },

    showActiveChangeError:function(){
        this.showMessage( 'There was a problem activating this business.' );
        return false;
    },

    showFeatureChangeError:function(){
        this.showMessage( 'There was a problem featuring this business.' );
        return false;
    },

    showFavoriteChangeError:function(){
        this.showMessage( 'There was a problem favoriting this business.' );
        return false;
    },

    showMessage:function( message, type ){
        var jsStatus = $('jsStatus');
        if( jsStatus ){
            if( typeof type == 'undefined' ){
                type = 'error';
            }
            jsStatus.className = type;
            jsStatus.innerHTML= '<p>' + message + '</p>';
            return true;
        }
        return false;
    },

    changeActiveResponse:function( response ){
        var activeResponse = Json.evaluate( response );
        if( activeResponse.error ){
            this.showMessage( activeResponse.errorMessage );
            return false;
        }

        // set as favorited
        if( activeResponse.listing_id ){
            if( $( 'business_listing_' + activeResponse.listing_id ) ){
                var listingContainer = $( 'business_listing_' + activeResponse.listing_id );
                if( $( 'loader_' + activeResponse.listing_id ) ){
                    listingContainer.removeChild( $( 'loader_' + activeResponse.listing_id ) );
                }
                if( activeResponse.action ){
                    var classString = listingContainer.className.toString();
                    classString.clean();
                    switch( activeResponse.action ){
                        case 'show':
                        if( $('hide_listing_' + activeResponse.listing_id ) ){
                            $('hide_listing_' + activeResponse.listing_id ).innerHTML = "Hide";
                        }
                        if( classString.contains('hidden') ){
                            listingContainer.removeClass('hidden');
                        }
                        break;
                        case 'hide':
                        if( $('hide_listing_' + activeResponse.listing_id ) ){
                            $('hide_listing_' + activeResponse.listing_id ).innerHTML = "Show";
                        }
                        if( !classString.contains('hidden') ){
                            listingContainer.addClass('hidden');
                        }
                        break;
                    } // end switch
                    this.showMessage( activeResponse.message, 'success' );
                    return true;
                }
            }
        }
        this.showFeatureChangeError();
        return false;
    },

    changeFeatureResponse:function( response ){
        var featureResponse = Json.evaluate( response );
        if( featureResponse.error ){
            this.showMessage( featureResponse.errorMessage );
            return false;
        }

        // set as favorited
        if( featureResponse.listing_id ){
            if( $( 'business_listing_' + featureResponse.listing_id ) ){
                var listingContainer = $( 'business_listing_' + featureResponse.listing_id );
                if( $( 'loader_' + featureResponse.listing_id ) ){
                    listingContainer.removeChild( $( 'loader_' + featureResponse.listing_id ) );
                }
                if( featureResponse.action ){
                    var classString = listingContainer.className.toString();
                    classString.clean();
                    switch( featureResponse.action ){
                        case 'featured':
                        if( $('feature_listing_' + featureResponse.listing_id ) ){
                            $('feature_listing_' + featureResponse.listing_id ).innerHTML = "UnFeature";
                        }
                        if( !classString.contains('featured') ){
                            listingContainer.addClass('featured');
                        }
                        break;
                        case 'unfeatured':
                        if( $('feature_listing_' + featureResponse.listing_id ) ){
                            $('feature_listing_' + featureResponse.listing_id ).innerHTML = "Feature";
                        }
                        if( classString.contains('featured') ){
                            listingContainer.removeClass('featured');
                        }
                        break;
                    } // end switch
                    this.showMessage( featureResponse.message, 'success' );
                    return true;
                }
            }
        }
        this.showFeatureChangeError();
        return false;
    },

    changeFavoriteResponse:function( response ){
        var favoriteResponse = Json.evaluate( response );
        if( favoriteResponse.error ){
            this.showMessage( favoriteResponse.errorMessage );
            return false;
        }

        // set as favorited
        if( favoriteResponse.listing_id ){
            if( $( 'business_listing_' + favoriteResponse.listing_id ) ){
                var listingContainer = $( 'business_listing_' + favoriteResponse.listing_id );
                if( favoriteResponse.action ){
                    var classString = listingContainer.className.toString();
                    classString.clean();
                    switch( favoriteResponse.action ){
                        case 'added':
                        if( $('favorite_listing_' + favoriteResponse.listing_id ) ){
                            $('favorite_listing_' + favoriteResponse.listing_id ).innerHTML = "unFavorite";
                        }
                        if( !classString.contains('favorite') ){
                            listingContainer.addClass('favorite');
                        }
                        break;
                        case 'removed':
                        if( $('favorite_listing_' + favoriteResponse.listing_id ) ){
                            $('favorite_listing_' + favoriteResponse.listing_id ).innerHTML = "Favorite";
                        }
                        if( classString.contains('favorite') ){
                            listingContainer.removeClass('favorite');
                        }
                        break;
                    } // end switch
                    this.showMessage( favoriteResponse.message, 'success' );
                    return true;
                }
            }
        }
        this.showFavoriteChangeError();
        return false;
    },

    changeFavorite:function( listing_id ){
        new Ajax("/directory/js/functions/changeFavorites.php",{
            method:'get',
            data:'listing_id=' + listing_id ,
            onComplete:this.changeFavoriteResponse.bind(this),
            onFailure:function( response ){ this.showFavoriteChangeError.bind( this ); }
        }).request();
    }

});