jQuery( function( $ ) {

    $('body').attr("id","business");

    if($.browser.msie) {
        $('div.wrapper').wrap('<div id="clearHeader"></div>');
        $('#function_overlay').css({
            left:'15px'
        });
    };

    $('#addressBlock li a').each(function(){
        if( $(this).text().length > 20 )
        {
            var beTxt = $(this).text().slice(0,20)+'...';
            $(this).text( beTxt );
        }
    })
	
    $('#otherPanos li a').click(function(){
        var image =  $(this)[0].className.split(':');
        if( image[2] == 'false' )
        {
            $('#embedLink').hide();
        }else{
            $('#embedLink').show();
        }
		
        if( typeof(deconcept) !== 'undefined' && deconcept.SWFObjectUtil.getPlayerVersion().major >= 6 ) {
            var so = new SWFObject('/javascripts/krpano/krpano.swf?108b9', 'krpanoSWFObject', '100%', '100%', '9,0,124,0','#000000');
            so.addParam('allowFullScreen','true');
            so.addParam('allowScriptAccess','always');
            so.addParam('bgcolor','#ebebeb');
            so.addParam('quality', 'autolow');
            so.useExpressInstall('/javascripts/krpano/swfobject/expressinstall.swf');
            so.addVariable('pano', '/krpano/business_page_embed/'+businessHandle+'/'+ image[0] +'.xml');
            so.addVariable('epd', '/data/embed/plugin_data/'+businessHandle );
            so.setAttribute('xiRedirectUrl', window.location);
            if ( so.write( 'mainPano' ) ) {
                //post-load functions here
                imageHandle = image[0];
                var url = '/data/get_description?id=' + image[3] + '&type=image';
                $("div#imageDescription").load(url)
                $("div#panos h2.imageTitle").text(image[1]);
                if ( getOS() == 'Windows' )
                {
                    //var wheelfix = new SWFkrpanoMouseWheel(so);
                }
            }
        }
        $('#showOnMap').attr('href', '/map#lat='+image[4]+'&lng='+image[5]+'&name='+image[0]+'&zoom=17');
        return false;
    })


    $('#getDirsLinkOpen').click( function(){
        $('#getDirections').show();
        $('#getDirsLinkClose').show();
        hidePano();
        $(this).hide();
    })

    $('#getDirsLinkClose').click( function(){
        $('#getDirections').hide();
        $('#getDirsLinkOpen').show();
        showPano();
        $(this).hide();
    })

    var Dmap;
    var directionsPanel;
    var directions;

    function initialize() {

        Dmap = new GMap2(document.getElementById("map_canvas"));
        directionsPanel = document.getElementById("returnedDirections");
        directionsPanel.innerHTML = '';
        Dmap.setCenter(new GLatLng(dMapLat, dMapLng), 12);
        directions = new GDirections(Dmap, directionsPanel);
        //GEvent.addListener(directions, "load", onGDirectionsLoad);
        GEvent.addListener(directions, "error", handleErrors);
        directions.load( $("#dir_from").val() + " to " + $("#dir_to").val() );

    }

    function handleErrors(){
        var errorMsg;
        if (directions.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
        {
            errorMsg = "No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + directions.getStatus().code;
        }else if (directions.getStatus().code == G_GEO_SERVER_ERROR)
        {
            errorMsg = "A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + directions.getStatus().code;

        }else if (directions.getStatus().code == G_GEO_MISSING_QUERY)
        {
            errorMsg = "The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + directions.getStatus().code;

        }else if (directions.getStatus().code == G_GEO_BAD_KEY)
        {
            errorMsg = "The given key is either invalid or does not match the domain for which it was given. \n Error code: " + directions.getStatus().code;

        }else if (directions.getStatus().code == G_GEO_BAD_REQUEST)
        {
            errorMsg = "A directions request could not be successfully parsed.\n Error code: " + directions.getStatus().code;

        }else errorMsg = "An unknown error occurred.";

        alert( errorMsg );
        directionsPanel.innerHTML = errorMsg;
    }


    $('#submit_dir').click( function(){
        initialize();
        return false;
    })

    $.updateLocTrail = function(handle,lat,lng,title,id)
    {
        var url = '/data/get_description?id=' + id + '&type=image';
        $("div#imageDescription").load(url)
        $("div#panos h2.imageTitle").text(title);
    }


    $('a.functionOverlay').click(function( ){
        var title;
        var modalHTML;
        var modal_content = $($(this).children('div')[0]).attr('id');
        if( modal_content == "linkIcon" ) {
            title = "Link to this page";
            modalHTML = 'link_form/business/' + businessHandle;
        } else if ( modal_content == "sendIcon" ) {
            title = "Send this page to a friend";
            modalHTML = 'send_to_friend_form/business/' + businessHandle;
        }
        triggerSendToFriendModal( modalHTML, title, modal_content );
        return false;
    });

})

function update_image(handle,lat,lng,title,id) {

    imageHandle = handle;
    imageName = unescape(title);
    $.updateLocTrail(handle,lat,lng,unescape(title),id);
	
}

function exit_fs(handle,lat,lng,title, id) {
    if( imageHandle != handle )
    {
        $.updateLocTrail(handle,lat,lng,unescape(title),id);
    }
}
