﻿/* Author: 

*/

var mapContent = 'continent';
var mapSpecifications = '';


$(function () {
	
	//.ie7 no-:before fix
	if($('html').hasClass('ie7')) {
		var $before = $('<div class="before"></div>');
		
		$('.main_column .content_group + .content_group').prepend($before)
	}
	
    //hide elements
    $('.idea_form ul').css('display', 'none');
    $('.more_tips').css('display', 'none');

    //submit tip form slide down
    $('.submit_tip h3').click(function () {
        $('.submit_tip ul').slideToggle(300);
    });

    //watermark
    if ($('.idea_form').length > 0) {
        $('.personal_information_field .name').watermark('Namn');
        $('.personal_information_field .email').watermark('E-postadress');
        $('.idea_field textarea').watermark('Skriv dina tips här');
    }

    //slide down more tips
    $('.view_more_tips').click(function () {
        $('.more_tips').slideToggle(300);
    });

    //change .view_more_tips text

    $('.view_more_tips').toggle(function () {
        $(this).text('Dölj tips');
    },
	function () {
	    $(this).text('Se fler tips');
	});

    //write map
	if ($('#map_alternatives').length > 0) {
        $.ajax({
            type: 'GET',
            url: '/View/Resources/Xml/map.xml',
            dataType: 'xml',
            success: xmlParser
        });

        $('.continent').live('click', function () {
            mapSpecifications = $(this).attr('id');
            $.ajax({
                type: 'GET',
                url: '/View/Resources/Xml/map.xml',
                dataType: 'xml',
                success: xmlParser
            });
        });

        $('.close_continent').live('click', function () {
            $('.continent_closeup').fadeOut(600, function () {
                $(this).remove();
            });

            $('#map_alternatives').html($('#map_alternatives_temp').html());
            $('#map_alternatives_header').hide();
        });


        //map interaction
        $('.continent').live('mouseenter', function () {
            $(this).find('.on').stop().fadeTo(200, 1);
        });

        $('.continent').live('mouseleave', function () {
            $(this).find('.on').stop().fadeTo(200, 0);
        });


        $('.country_marker').live('mouseenter', function () {
            $(this).find('.marker_label').css('display', 'block');
            var maxWidth = $(this).width();
            $(this).find('.marker_label').css('max-width', maxWidth);
            $(this).find('.marker_label').stop().fadeTo(100, 1);
        });

        $('.country_marker').live('mouseleave', function () {
            $(this).find('.marker_label').stop().fadeTo(100, 0, function () {
                if ($(this).parent('.country_marker').is(':not(.active)'))
                    $(this).css({ 'display': 'none', 'max-width': 'none' });
            });
        });

        $('.country_marker').live('click', function () {
            $('.country_marker.active').not(this).find('.marker_label').animate({ fontSize: '12px' }, 100, function () {
                var maxWidth = $(this).width();
                $(this).css('max-width', maxWidth);
                $(this).animate({ opacity: 0 }, 100, function () {
                    $(this).parent('.country_marker').removeClass('active');
                });
                $(this).css('max-width', 'none');
            });

            var countryName = $(this).find('.marker_label').html();
            getPlaceTaggedArticlesInCountry(countryName);
            $('#map_alternatives_header').html(countryName);

            $(this).find('.marker_label').css('max-width', 'none');
            $(this).find('.marker_label').stop().animate({ fontSize: '18px' }, 150);
            $(this).addClass('active');
        });

        $('.country_listitem').live('click', function () {
            getPlaceTaggedArticlesInCountry($(this).html());
            $('#map_alternatives_header').html($(this).html());
            //TODO: Highlight countrymarker on list click
        });

        $('.country_marker.active').live('click', function () {
            $(this).find('.marker_label').stop().animate({ fontSize: '12px' }, 100);
            $(this).removeClass('active');
        });

        $('.continent_africa').live('click', function () {
            loadContinent('africa');
        });

        $('.continent_asia').live('click', function () {
            loadContinent('asia');
        });

        $('.continent_europe').live('click', function () {
            loadContinent('europe');
        });

        $('.continent_north_america').live('click', function () {
            loadContinent('northamerica');
        });

        $('.continent_south_america').live('click', function () {
            loadContinent('southamerica');
        });

        $('.continent_oceania').live('click', function () {
            loadContinent('oceania');
        });

    }
	
	if($('.book_info').length > 0)
		$('#container').addClass('book_article');
	
});

function loadContinent(continent) {
    mapSpecifications = continent; // global var. find in script.js
    $.ajax({
        type: 'GET',
        url: '/View/Resources/Xml/map.xml',
        dataType: 'xml',
        success: xmlParser
    });
}

function setCountryResults(countries) {
    if (countries.length != 0) {
        var html = '';
        for (var i = 0; i < countries.length; i++) {
            html = html + "<li><a href=\"#\" class=\"country_listitem\">" + countries[i] + "</a></li>";
        }
        $('#map_alternatives').html(html);
    }
}

function getArticleImgBySeries(series) {
    var img;
    if (series != null) {
      	if (series.toLowerCase().indexOf("berlitz") == 0) {
      		img = "/View/Resources/Images/berlitz_t.png";
      	}
      	else if (series.toLowerCase().indexOf("första klass") == 0) {
      		img = "/View/Resources/Images/forsta_klass_t.png";
      	}
      	else if (series.toLowerCase().indexOf("topp 10") == 0) {
      		img = "/View/Resources/Images/topp10_t.png";
        }
        else if (series.toLowerCase().indexOf("miniguider") == 0) {
            img = "/View/Resources/Images/miniguides_t.png";
        }

        }

    return img;
}



function xmlParser(xml) {
    if (mapSpecifications != '') {
        var backgroundPosition = 'center center';

        if (mapSpecifications == 'oceania') var backgroundPosition = '63% center';
        if(mapSpecifications == 'africa') var backgroundPosition = '56.5% center';

        var worldMap = $('.world_map');
        if(worldMap != null)
            worldMap.append('<div class="continent_closeup ' + mapSpecifications + '" style="background-image: url(/View/Resources/Images/map_img/' + mapSpecifications + '.png); background-position:' + backgroundPosition + ';"></div>');
        
        $('.continent_closeup').fadeIn(600);


        $('#map_alternatives').html('');
        $('#map_alternatives_header').html($(xml).find('continent[name="' + mapSpecifications + '"]').attr('name_sv'));
        $('#map_alternatives_header').show(); 


        $(xml).find('continent[name="' + mapSpecifications + '"]').children().each(function () {
            var id = $(this).attr('name');
            var left = $(this).attr('x');
            var top = $(this).attr('y');
            var content = $(this).text();
            var marker = Math.floor(Math.random() * 4);

            /**/
			$('#map_alternatives').append("<li><a href=\"#\" class=\"country_listitem\">" + content + "</a></li>");
            /**/
            $('.continent_closeup').append('<div class="country_marker marker_' + marker + '" id="' + id + '" style=" top: ' + top + 'px; left: ' + left + 'px;" ><a class="marker_label">' + content + '</a></div>');
        });
        var showBackToStartPage = $("#ShowBackToStartPage");
        if (showBackToStartPage.length > 0) {
            $('#map_alternatives').append("<li><a class='backToStart' href='/' title='Tillbaka till startsidan'>Tillbaka till kartan</a></li>"); 
        }
        else {
            $('#map_alternatives').append("<li><div class=\"close_continent\" style=\"width: 60px; position: relative; float: right; background: none;\">Tillbaka</div></li>");
        }
        
        $('.continent_closeup').append('<div class="close_continent"></div>');
        return;
    }

    $(xml).find(mapContent).each(function () {
        var id = $(this).attr('name');
        var width = $(this).attr('width');
        var height = $(this).attr('height');
        var left = $(this).attr('x');
        var top = $(this).attr('y');
        var zindex = 2;

        var worldMap = $('.world_map');
        if (worldMap != null)
            worldMap.append('<div id="' + id + '" class="continent" style="width: ' + width + 'px; height: ' + height + 'px; top:' + top + 'px; left:' + left + 'px; z-index:' + zindex + '"><img class="on" src="/View/Resources/Images/map_img/' + id + '_On.gif"/></div>');
    });
}

/***************************
        SEARCH
 ***************************/

// Search
function search_delay(element) {
    var func = function () { searchArticles(element); };
    if (element.zid) {
        clearTimeout(element.zid);
    }
    element.zid = setTimeout(func, 500);
}

function searchArticles(element) {
    var res;
    var phrase = $(element).val();
    if (phrase.length > 0) {
        $.ajax({
            type: "POST",
            url: "/Base/WebServices/SearchArticles.asmx/Search",

            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ searchPhrase: phrase }),
            dataType: "json",
            processData: false,
            success: function (data, textStatus) {
                res = data.d;
                setSearchResults(res);
            }
        });
    }
    return res;
}

function getPlaceTaggedArticlesInCountry(phrase) {
    var res;
    if (phrase.length > 0) {

        $.ajax({
            type: "POST",
            url: "/Base/WebServices/SearchArticles.asmx/GetPlaceTaggedArticlesInCountry",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ searchPhrase: phrase }),
            dataType: "json",
            processData: false,
            success: function (data, textStatus) {
                res = data.d;
                setPlaceTaggedResults(res);
            }
        });
    }
    return res;
}

function setPlaceTaggedResults(articles) {
   	var partnerUrlPart = $('#hidden_partner_url');
   	if (partnerUrlPart != null)
   		partnerUrlPart = partnerUrlPart.val();

   	$('#map_alternatives').html('');
   	if (articles.length != 0) {
   		var html = '';
   		for (i = 0; i < articles.length; i++) {
   			var seriesLogoSrc = getArticleImgBySeries(articles[i].Series);
   			var img = "<img src=\"" + seriesLogoSrc + "\" alt=\"\" />";
   			var title = articles[i].Title;
   			if (title.length > 23)
   				title = title.substring(0, 23);
   			html = html + "<li>" + img + "<a class=\"title\" href=\"" + partnerUrlPart + articles[i].Url + "\" >" + title + "</a></li>";
   		}
   		$('#map_alternatives').append(html);
    }
     var showBackToStartPage = $("#ShowBackToStartPage");
     if (showBackToStartPage.length > 0) {
         $('#map_alternatives').append("<li><a class='backToStart' href='/' title='Tillbaka till startsidan'>Tillbaka till kartan</a></li>");
     }
     else {
         $('#map_alternatives').append("<li><div class=\"close_continent\" style=\"width: 60px; position: relative; float: right; background: none;\">Tillbaka</div></li>");
     }
}


/* Search end */
