/**
 * Project:
 * Hansainvest - Worldmap for estates
 *
 * Description:
 * This file contains functions for toggling maps bettween world, contintent and country view
 * Animations were defined by jquery
 *
 * @version 1.0.0
 * @author     Timo Trautmann
 * @copyright  four for business AG <www.4fb.de>
 * @requirement jQuery 1.2.6
 *
 * {@internal
 * created 2008-11-05
 *
 *  $Id$:
 * }}
 *
 */

//hash stores which images were already preloaded 
var aLoadedObjects = Object();
var iCounter = 0;
var iMapCount = 0;
var sCurMap = 'world';
 
//if javascript is possible remove hard coded links for users who does not has javascript enabled
$(document).ready(function () {
    $('#card_container').css('background-image', 'url(images/loading.gif)');
    $('#card_container').css('background-repeat', 'no-repeat');
    $('#card_container').css('background-position', 'center');
    $('#world_card').attr('src', 'images/spacer.gif');
    $('#map_container area').attr('href', 'javascript://');
    imagePreloader(sInitMap);
});

/**
   * Function preloads images in order for a faster toggle
   *
   * @param sting sCard - name of map to load images for (optional, default world is loaded)
   */
function imagePreloader(sCard) {
    var aCacheImages = new Array();

    //load world map images by default
    if (!sCard) {
        sCard = 'world';
    }
    
    //if images for current map were already loaded, cancel process
    if (aLoadedObjects[sCard] && aLoadedObjects[sCard] == 'true') {
        toggle_to_map(sCard, true);
        return;
    } else {
        aLoadedObjects[sCard] = 'true';
    }
    
    for (var sKey in aCardInfos) {
        for (var sKey2 in aCardInfos[sKey]) {
            if (sKey2 != 'main_width' &&
                sKey2 != 'main_height' &&
                sKey2 != 'main_map_tpl' &&
                sKey == sCard) {
                aCacheImages.push('images/maps/'+aCardInfos[sKey][sKey2]);
            }
        }
    }
    
    doImageLoad(aCacheImages, sCard);
}

/**
   * Function loads images into browsercache by creating new image objects 
   * an calls catchLoadComplete() to detect when loading is complete
   *
   * @param, array aCacheImages - images to load
   * @param string sCard - map of images to load for
   */
function doImageLoad(aCacheImages, sCard) { 
    //reset global counter for completion detection
    iCounter = 0;
    for (var i=0; i < aCacheImages.length; i++) {
        var oPreloadImage = new Image();
        $(oPreloadImage).attr('src', aCacheImages[i]);
        $(oPreloadImage).load(function () {catchLoadComplete(aCacheImages.length, sCard);});
    }
}

/**
   * Function increments counter an detects when a image loading process
   * is completed
   *
   * @param, integer - iSumImages - sum of images which should be loaded in this process
   * @param string sCard - map of images to load for
   */
function catchLoadComplete(iSumImages, sCard) {
    iCounter++;
    if (iSumImages == iCounter) {
        toggle_to_map(sCard, true);
    }
}

/**
   * Funcion hilights a subpart of a map for selection
   *
   * @param string sCard - name of global  corresponding card (world, europe) 
   * @param string sSubArea - name of subarea to higlight (europa on worldmap)
   */
function highlight_area(sCard, sSubArea) {
    $('#world_card').attr('src', 'images/maps/'+aCardInfos[sCard][sSubArea]);
}

/**
  * Function resets a selected area of map
  *
  * @param sCard - name of corresponding active map
  */
function reset_card(sCard) {
	if (sCurMap == sCard) {
		$('#world_card').attr('src', 'images/maps/'+aCardInfos[sCard]['main']);
	}
}

/**
  * Function toggles from one map to another
  *
  * @param sMap - name of map to display
  * @param bLoadComplete -  by default false (this function is recalled when all neccessary images for view were preloaded)
  */
function toggle_to_map(sMap, bLoadComplete) {
    //if there are no infos for current map, cancel process
    if (!aCardInfos[sMap]) {
        return;
    }
    
	sCurMap = sMap;
	
    if (!bLoadComplete) {
        $('#world_card').fadeOut('fast');
        $('#map_details').fadeOut('fast');
        $("#map_immoobjects").empty();
        //preload over images for map
        imagePreloader(sMap)
    } else {
        //delete all image map informations
        $('#map_card_container').remove();
		$('#world_card').attr('usemap', '');
		
        //hide current map
        $('#world_card').fadeOut('fast', function() {
            //replace image (in this point image is display:none)
            
            $('#world_card').attr('src', 'images/maps/'+aCardInfos[sMap]['main']);
            
            window.setTimeout("renderMap('"+sMap+"')" , 100);
        });
    }
}

function renderMap(sMap) {
    //resize area to size of new map
    $("#card_container").animate({ 
        width: $('#world_card').width()+'px',
        height: $('#world_card').height()+20+'px'
      }, 500, null, function () {
        $('#map_area').html(' - '+aMapTranslations[sMap]);
        if (aCardInfos[sMap]['main_map_tpl']) {
            //replace image (in this point image is display:none)
            $('#world_card').attr('src', 'images/maps/'+aCardInfos[sMap]['main']);
            //show new map
            $('#world_card').fadeIn('fast', function () {
                //load corresponding image map for clickable sections (countries) on this map (remove non js links)
                $("#map_container").load('templates/img_maps/'+aCardInfos[sMap]['main_map_tpl'], function () { 
                    $('#map_container area').attr('href', 'javascript://');
                    
                    //replace translations
                    var sString = $('#map_container').html();
                    for (var sKey in aMapTranslations) {
                        var expression = new RegExp('{'+sKey+'}', 'ig');
                        sString = sString.replace(expression, aMapTranslations[sKey]);
                    }
                    $('#map_container').html(sString);
                    
                    iMapCount++;
                    $('#map_card_container').attr('name', 'map_card_container_'+iMapCount);
                    $('#world_card').attr('usemap', '#map_card_container_'+iMapCount);
                });
                $("#map_container").css('display', 'block');
                $("#world_card").css('display', 'block');
                $("#map_details").css('display', 'none');
                $("#map_immoobjects").css('display', 'none');
            });
        } else {
            //replace image (in this point image is display:none)
            $('#world_card').attr('src', 'images/spacer.gif');
            $("#map_container").css('display', 'none');
            $("#world_card").css('display', 'none');
            $("#map_immoobjects").css('display', 'block');
            //load corresponding image map for clickable sections (countries) on this map (remove non js links)
            $("#map_details").load('front_content.php?idart=1537&map='+sMap, function () {
                $("#map_details").fadeIn('fast');
                $('#deutschlandkarte a').attr('href', 'javascript://');
                $("div.geoobjekt").each(function () {$("#map_immoobjects").append(this)});              
                //replace translations
                var sString = $('#map_details').html();
                for (var sKey in aMapTranslations) {
                    var expression = new RegExp('{'+sKey+'}', 'ig');
                    sString = sString.replace(expression, aMapTranslations[sKey]);
                }
                $('#map_details').html(sString);
                initClickEvents();
            });
            //show new map
        }
    });
}

/**
   *   Function displays in backend form for getting longtitude and latidude of a city
   *
   */
function getPosition() {
    var sHtml =  '<div id="search_position" style="border: 1px solid #BCCBE6; z-index:1000; display:none; width:350px; height: 130px; background-color:#dde5f2; position: absolute; top:50px; left:50px; color:#000; padding: 3px;">';
        sHtml += '  <div style="float:right; padding-right: 3px;">';
        sHtml += '      <a href="javascript://" onclick="mapClose();">X</a>';
        sHtml += '  </div>';
        sHtml += '  <h2 style="cursor: move;">L&auml;ngen- und Breitengrade bestimmen</h2>';
        //sHtml += '    <form name="map_lat_lon_search" id="map_lat_lon_search" method="post" action="javascript://">';
        sHtml += '  <label style="float:left; width:100px; height:18px;" for="map_street">Stra&szlig;e: </label>';
        sHtml += '  <input id="map_street" type="text" style="float:left; width:200px; height:18px;" name="map_street">';
        sHtml += '  <label style="float:left; width:100px; height:18px;" for="map_zip">Postleitzahl: </label>';
        sHtml += '  <input id="map_zip" type="text" style="float:left; width:200px; height:18px;" name="map_zip">';
        sHtml += '  <label style="float:left; width:100px; height:18px;" for="map_city">Ort: </label>';
        sHtml += '  <input id="map_city" type="text" style="float:left; width:200px; height:18px;" name="map_city">';
        sHtml += '  <label style="float:left; width:100px; height:18px;" for="map_country">Land: </label>';
        sHtml += '  <input id="map_country" type="text" style="float:left; width:200px; height:18px;" name="map_country">';
        sHtml += '  <div style="margin-top: 5px; float:left;">';
        sHtml += '      <input style="margin-right: 15px;" type="submit" name="map_search" value="Koordinaten suchen" onclick="doMapSearch(); return false;">';
        sHtml += '      <span id="map_notice" style="color:red;"></span>';          
        sHtml += '  </div>';
        sHtml += '  <div style="clear:both"></div>';
        sHtml += '  ';
        sHtml += '  <div id="map_results" style="display:none;">';
        sHtml += '      <hr style="border-color:#BCCBE6; padding:5px;"/>';
        sHtml += '      <label style="float:left; width:100px; height:18px;" for="map_search_results">Ergebnisse: </label>';
        sHtml += '      <div style="width:200px; float:left;" id="search_result_spacer"></div>';
        sHtml += '      <input type="submit" style="margin-top: 5px; float:left;" name="map_select" value="Koordinaten &uuml;bernehmen" onclick="doRetriveLatLon(); return false;">';
        sHtml += '      <div style="clear:both"></div>';
        sHtml += '  </div>';
        //sHtml += '    </form>';
        sHtml += '</div>';
    $('#be_map_position').parent().append(sHtml);
    var aPosition = $('#map_picture_edit').position();
    
    var iLeft = 35;
    var iTop = 0;
    
    if($.browser.msie){
        iLeft = 315;
        iTop = 160;
    }
    
    $('#search_position').css('left', aPosition['left']+iLeft+'px');
    $('#search_position').css('top', aPosition['top']+iTop+'px');
    $('#search_position').fadeIn('fast');

    if ($('#HTMLTEXT_17_101').html() != '' && $('#HTMLTEXT_17_101').html() != '&nbsp;')
        $('#map_street').attr('value', $('#HTMLTEXT_17_101').html());
    
    if ($('#HTMLTEXT_17_102').html() != '' && $('#HTMLTEXT_17_102').html() != '&nbsp;')
        $('#map_zip').attr('value', $('#HTMLTEXT_17_102').html());
        
    if ($('#HTMLTEXT_17_103').html() != '' && $('#HTMLTEXT_17_103').html() != '&nbsp;')
        $('#map_city').attr('value', $('#HTMLTEXT_17_103').html()); 
		
	$('#search_position').draggable({handle: 'h2'});
}

/**
  * Function retrives informations, put them onto site and close searchbox
  *
  */
function doRetriveLatLon() {
    var sValue = $('#map_search_results').attr('value');
    
    var aData = sValue.split(';');
    var aLat = aData[0].split(':');
    var aLon = aData[1].split(':');
    var aCountry = aData[2].split(':');
    $('#HTMLTEXT_17_997').html(aLon[1]);
	aEditdata['HTMLTEXT_17_997'] = aLon[1];
    $('#HTMLTEXT_17_998').html(aLat[1]);
	aEditdata['HTMLTEXT_17_998'] = aLat[1];	
	$('#HTMLTEXT_17_996').html(aCountry[1]);
	aEditdata['HTMLTEXT_17_996'] = aCountry[1];
    
    if ($('#map_street').attr('value') != '') {
        $('#HTMLTEXT_17_101').html($('#map_street').attr('value'));
		aEditdata['HTMLTEXT_17_101'] = $('#map_street').attr('value');
    }
    
    if ($('#map_zip').attr('value') != '') {
        $('#HTMLTEXT_17_102').html($('#map_zip').attr('value'));
		aEditdata['HTMLTEXT_17_102'] = $('#map_zip').attr('value');
    }
    
    if ($('#map_city').attr('value') != '') {
        $('#HTMLTEXT_17_103').html($('#map_city').attr('value'));
		aEditdata['HTMLTEXT_17_103'] = $('#map_city').attr('value');
    }
    
    mapClose();
}

/**
  * Function closes map for latidude and longtitude search
  *
  */
function mapClose() {
    $('#search_position').fadeOut('fast', function () {
        $('#search_position').remove();
    });
}

/**
  * Function da a ajax call for getting matching positions on users search informations
  *
  */
function doMapSearch() {
    $('#map_notice').html('');

    var aQueryString = Array();
    if ($('#map_street').attr('value') != '') {
        aQueryString.push($('#map_street').attr('value'));
    }
    
    if ($('#map_zip').attr('value') != '') {
        aQueryString.push($('#map_zip').attr('value'));
    }
    
    if ($('#map_city').attr('value') != '') {
        aQueryString.push($('#map_city').attr('value'));
    }
    
    if ($('#map_country').attr('value') != '') {
        aQueryString.push($('#map_country').attr('value'));
    }
    
    var sQueryString = encodeURI(aQueryString.join(' '));

    $.ajax({
        global: false,
        type: "POST",
        url: sConClientPath+'include.latlonrequ.php',
        data: "query_string="+sQueryString,
        success: function(sTpl){
            if (sTpl == '') {
                $('#map_results').css('display', 'none');
                $("#search_position").animate({ 
                    height: '130px'
                }, 300, null, function () {
                    $('#map_notice').html('Keine passenden Daten gefunden.');
                    $('#search_result_spacer').html();
                });
            } else {
                $("#search_position").animate({ 
                    height: '195px'
                }, 300, null, function () {
                    $('#search_result_spacer').html(sTpl);
                    $('#map_results').fadeIn('fast;');
                    $('#map_search_results').css('width', '200px');
                });
            }
        }
    });
}
