var re = new RegExp("^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$");

var map = null;

var clusterMarkers = [];

$(document).ready(function() {
	
	// Cufon
	Cufon('h3:not(.nocufon) a', { hover: { color: '#0089e0' } });
	Cufon.replace('h1:not(.nocufon), h2:not(.nocufon), h3:not(.nocufon)');
	
	$("#locate").click(function(){
		if (navigator.geolocation) {
			navigator.geolocation.getCurrentPosition(
	 			function (position) {
	 
					// Did we get the position correctly?
					//alert (position.coords.latitude);
	 
					// To see everything available in the position.coords array:
					//for (key in position.coords) {alert(key)}
	 
					$.ajax({
						type: "POST",
						url: "ajax/nearMe.php",
						data: "lat=" + position.coords.latitude + "&lon=" + position.coords.longitude,
						dataType: "json",
						success: function(response) {
							var place = response.place;
							var html = '<div class="phoney">';
							html += '<div class="phoneytext"><a href="index.php?content=place&id=' + place.id + '"><span><img src="http://www.clusttour.gr/content/icons/' + place.local_thumb_url + '" alt="' + place.name + '" width="24" height="24" /></span>' + place.name + '</a></div>';
							html += '<div style="position: absolute; right: 32px; height: 0pt; width: 0pt; margin-left: 0pt; border-width: 10px 0pt 0pt 10px; border-color: rgb(44, 44, 44) transparent transparent; border-style: solid;"></div>';
							html += '</div>';
							
							$(html).insertAfter($("#locate"));
							$(".phoney").fadeIn();
						}
					});
	 
				}, 
				// next function is the error callback
				function (error) {
					switch(error.code) {
						case error.TIMEOUT:
							alert ('Timeout');
						break;
						case error.POSITION_UNAVAILABLE:
							alert ('Position unavailable');
						break;
						case error.PERMISSION_DENIED:
							alert ('Permission denied');
						break;
						case error.UNKNOWN_ERROR:
							alert ('Unknown error');
						break;
					}
				}
			);
		}
	});
	
	// Tabs
	// $("ul.css-tabs").tabs("div.css-panes > div", { history: true });

    $("#searchInput").focus();

    $("#signInDiv").click(function(event){
        var pos = $("#signInDiv").offset();
        $("#loginWidget").css( {
            "left": (pos.left) + "px",
            "top":(pos.top+36) + "px"
            } );
        openCloseloginWidget();
        event.stopPropagation();
    });

    /*$(".imageThumbDiv1").hover(function(){
        $(this).find(".voteThumb").fadeIn();
    },function(){
        $(this).find(".voteThumb").fadeOut();
    });*/

    $(".oneMemberDiv").hover(function(){
        $(this).find('.MemberDescription').fadeIn();
    },function(){
        $(this).find('.MemberDescription').fadeOut();
    });

    $(".questionLi").click(function(){
        var target = $(this).attr('scrollTo');
        $('html, body').animate({
            scrollTop: $("#"+target).offset().top
        }, 800);
    });

    $(".backToTop").click(function(){
        $('html, body').animate({
            scrollTop: 0
        }, 400);
    });

    $("#blogPageSelect").change(function(){
        var page = $(this).val();
        window.location.href = '?content=blog&page='+page;
    });

    $("#loginButton").click(function(){
        var username = $("#usernameLogin").val();
        var password = $("#passwordLogin").val();

        if(!re.test(username)) {
            alert("Please double check the E-mail");
        } else if(password.length<8) {
            alert("Hmmm... the password does not have at least 8 characters");
        }else {
            $.ajax({
                type: "POST",
                url: "ajax/login.php",
                data: "username="+encodeURIComponent(username)+"&password="+encodeURIComponent(password),
                dataType: "json",
                success: function(responce){
                    if(responce.success == true) window.location.reload();
                    else alert("Login failed!");
                }
            });
        }
    });

    $("#toggleMapHeight").click(function(){
        var extra = 200;
        var height = $("#map").height();
        if(height==314) {
            $("#map").height(height+extra);
            $("#toggleImage").attr("src","images/close.png");
        }
        else {
            $("#map").height(height-extra);
            $("#toggleImage").attr("src","images/expand.png");
        }
    });

    $(".cityRequest").hover(function(){
        $("#addNormal").hide();
        $("#add").show();
    }, function(){
        $("#add").hide();
        $("#addNormal").show();
    });

    $(".cityRequest").click(function(){
        $("#feedback_type").val("1");
        $("#contactFormDiv").dialog("option","title","I have a city request");
        $("#imageCF").attr("src", "images/add.png");
        $("#textCF").val("The city I would like to see in ClustTour is:\r\n\r\n");
        $("#contactFormDiv").dialog("open");
    });

    $(".idea").hover(function(){
        $("#ideaNormal").hide();
        $("#idea").show();
    }, function(){
        $("#idea").hide();
        $("#ideaNormal").show();
    });

    $(".idea").click(function(){
        $("#feedback_type").val("2");
        $("#contactFormDiv").dialog("option","title","I have a great idea");
        $("#imageCF").attr("src", "images/idea.png");
        $("#textCF").val("Here is my great idea I would like to share with you:\r\n\r\n");
        $("#contactFormDiv").dialog("open");
    });

    $(".question").hover(function(){
        $("#questionNormal").hide();
        $("#question").show();
    }, function(){
        $("#question").hide();
        $("#questionNormal").show();
    });

    $(".question").click(function(){
        $("#feedback_type").val("3");
        $("#contactFormDiv").dialog("option","title","I have a question to ask");
        $("#imageCF").attr("src", "images/question.png");
        $("#textCF").val("Well, what I would like to ask is...\r\n\r\n");
        $("#contactFormDiv").dialog("open");
    });

    $("#submitCF").click(function(){
        var feedback_type = $("#feedback_type").val();
        var name = $("#nameCF").val();
        var email = $("#emailCF").val();
        var text = $("#textCF").val();

        if(name == "") {
            alert("Please enter your name.")
            $("#nameCF").focus();
        } else if(!re.test(email)) {
            $("#emailCF").focus();
            alert("Please enter your E-mail.")
        } else {
            $.ajax({
                type: "POST",
                url: "ajax/saveFeedback.php",
                data: "feedback_type="+feedback_type+"&name="+encodeURIComponent(name)+"&email="+encodeURIComponent(email)+"&text="+encodeURIComponent(text)+"&timestamp="+Math.round((new Date()).getTime()/1000),
                dataType: "json",
                success: function(responce){
                    if(responce.success == true) {
                        if(feedback_type==1) alert("We will examine your city request. Thank you!");
                        else if(feedback_type==2) alert("If great minds really meet, we will implement your idea. Thank you!");
                        else alert("That was a great question! You will hear from us soon! Thank you!");
                        $("#contactFormDiv").dialog("close");
                    }
                }
            });
        }
    });

    /**
     * Page Select
     */
    $(".pageSelect").change(function(){
	window.location.href = $(this).val();
    });

    /** Contact Form **/
    $("#contactFormDiv").dialog({
        modal: true,
        width: 400,
        height: 400,
        autoOpen: false,
        resizable: false
    });

    /** TIME SLICES **/
    var title = '';

    $(".TimeSlice").click(function(){
	$(".TimeSlice").removeClass("boldText");
	$(this).addClass("boldText");
	if(title=='') title = $("#title1").html();
	$("#title1").html(title+" @ "+$(this).html());
	$('html, body').animate({scrollTop:0}, 'slow');
	try {am.clearMap();} catch(e) {}
	$.ajax({
	    type: "POST",
	    url: "ajax/clustersOfTimeSlice.php",
	    data: "ts_id="+$(this).attr("time_slice_id"),
	    dataType: "json",
	    success: function(responce){
		ooo = responce;
		for(i=0; i<clusterMarkers.length; i++) clusterMarkers[i].setMap(null);
		var marker = null;
		var title = '';
		var clusterInfowindow = null;
		var clusterInfowindowContent = '';
		var icon = '';
		for(var i=0; i<responce.clusters.length; i++) {
		    clusterInfowindowContent = '';
		    title = (responce.clusters[i].cluster.title!="") ? responce.clusters[i].cluster.title : "No title";
		    icon = ((responce.clusters[i].cluster.type==1) ? CT.photoclusterPoiIcon : CT.photoclusterEventIcon);
		    marker = new google.maps.Marker({
			position: new google.maps.LatLng(responce.clusters[i].cluster.latitude,responce.clusters[i].cluster.longitude),
			map: map,
			title: title,
			icon: icon,
			myData: {
			    clusterId: responce.clusters[i].cluster.id
			}
		    });

		    clusterInfowindowContent += '<div class="iw_areaTitle"><a href="?content=cluster&id='+marker.myData.clusterId+'">'+title+'</a></div>';
		    clusterInfowindowContent += '<div class="iw_photoThumbnails">';
		    for(var j=0; j<responce.clusters[i].photos.length; j++) {
			clusterInfowindowContent += '<img class="infoWindowThumbnail oneThumbnail" photo_id="'+responce.clusters[i].photos[j].id+'" photo_original_id="'+responce.clusters[i].photos[j].original_id+'" src="'+responce.clusters[i].photos[j].host_prefix_name+responce.clusters[i].photos[j].local_thumb_url+'" title="'+responce.clusters[i].photos[j].title+'" width="80" height="80" />';
		    }
		    clusterInfowindowContent += '</div>';
		    clusterInfowindowContent += '<div class="iw_areaTags">';
		    for(j=0; j<responce.clusters[i].tags.length; j++) {
			clusterInfowindowContent += "<a href=\"?content=tag&id="+responce.clusters[i].tags[j].id+"\">"+responce.clusters[i].tags[j].tag+"</a>, ";
		    }
		    clusterInfowindowContent = clusterInfowindowContent.substring(0,clusterInfowindowContent.length-2);
		    clusterInfowindowContent += '</div>';

		    clusterInfowindow = new google.maps.InfoWindow({});

		    marker.myData.infowindowContent = clusterInfowindowContent;

		    google.maps.event.addListener(marker, 'click', function() {
			clusterInfowindow.setContent(this.myData.infowindowContent);
			clusterInfowindow.open(map,this);
		    });

		    clusterMarkers.push(marker);
		}
	    }
	});
    });


    /*********************/
    $("#window").dialog({
        autoOpen: false,
        width:700,
        height:400,
	resizable:false
    });

    $("#loginRegisterFacebook").click(function(){
        $("#window").dialog('open');
    });

    //$("#photoWindow").dialog({
    //    autoOpen: false,
	//width: 700,
	//height: 500,
	//resizable: false
	//});

    //$(".oneThumbnail").click(function(){
	//loadPhoto($(this).attr("photo_id"),$(this).attr("photo_original_id"));
    //});
	$(".oneThumbnail").overlay({
			effect: 'apple',
			mask: '#111',
			onBeforeLoad: function() { clearPhotoWindow(); loadPhoto(this.getTrigger().attr("photo_id"),this.getTrigger().attr("photo_original_id")) }
	});

    //$(".oneThumbnail").live("click",function(){
	//loadPhoto($(this).attr("photo_id"),$(this).attr("photo_original_id"));
	//});

    $(".linkToFlickrPage").live("click",function(){
	showOriginalPage($(this).attr("photo_id"));
    });

    /**
     * SEARCH
     */
    $("#searchInput").keyup(function(event){
	if (event.keyCode == '13') {
            doSearch();
        }
    });

    $(".searchLight").click(function(){
	doSearch();
    });
    

    /**
     * Map
     */
    initializeMap()
});

var doSearch = function() {
    var keywords = $("#searchInput").val();
    if(keywords.length>2) {
	keywords = keywords.split(" ");
	window.location.href = "?content=search&keywords="+keywords.join("+");
    }
}

var openCloseloginWidget = function() {
   if($("#loginWidget").css("display")=="none") {
       $("#signInDiv").addClass("SignInActive");
       $("#loginWidget").show('slow',function(){
           $("#usernameLogin").focus();
       });
   }
   else {
       $("#signInDiv").removeClass("SignInActive");
       $("#loginWidget").hide('slow');
   }
}



var loadingStart = function() {
    $('body').css('cursor', 'wait');
}

var loadingStop = function() {
    $('body').css('cursor', 'default');
}





var loadPhoto = function(photo_id,original_photo_id) {
    loadingStart();
    $.getJSON('http://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=ebdb8e3596d2cf4c5987023970a6a04a&photo_id='+original_photo_id+'&format=json&jsoncallback=?',
    function(data){
		if (data.stat == 'fail' || data.photo.visibility.ispublic == '0') {
			$("#photoThumb").attr("src","images/default_image.jpg");
			$("#photoThumb").attr("width","140");
			$("#photoThumb").attr("height","140");
			$("#photoThumb").attr("title","Not found");
			$("#photoTitle").html('Not found');
			$("#photoOriginalURL").attr("target", "");
			$("#photoOriginalURL").attr("href","javascript: void(0);");
			$("#photoDescription").html(data.message);
			$("#photoUserURL").attr("href","");
			$("#photoUserURL").html("-");
			$("#photoDate").html("-");
			$("#photoWindowContentDiv").animate({ opacity: 1 });
			loadingStop();
		}
		else {
			
			// Thumb
			setOriginalPhoto(original_photo_id);
			
			// Title
			var title = ((data.photo.title._content) ? data.photo.title._content : "No title");
			$("#photoThumb").attr("title", title);
			$("#photoTitle").html(title);
			
			// User
			setUserPage(data.photo.owner.nsid);
			$("#photoUserURL").html(data.photo.owner.username);
			
			// Date
			$("#photoDate").html(data.photo.dates.taken);
			
			// Original URL
			$("#photoOriginalURL").attr("target", "_blank");
			$("#photoOriginalURL").attr("href", data.photo.urls.url[0]._content);
			
			// Description
			var description = ((data.photo.description._content) ? data.photo.description._content : "No description");
			$("#photoDescription").html(description.replace(/\n{2}/g,'\n').replace(/\n/g,'<br />'));
			
			// Tags
			for (var i = 0; i < data.photo.tags.tag.length; i++) {
				if (!data.photo.tags.tag[i].machine_tag) {
					$("#photoTags").append('<li><a href="index.php?content=tag&q=' + encodeURIComponent(data.photo.tags.tag[i].raw) + '">'+data.photo.tags.tag[i].raw+'</a></li> ');
				}
			}
			
			$("#photoWindowContentDiv").animate({ opacity: 1 });
			loadingStop();
			
		}
    });    
}

var setOriginalPhoto = function(original_photo_id) {
    $.getJSON('http://api.flickr.com/services/rest/?method=flickr.photos.getSizes&api_key=ebdb8e3596d2cf4c5987023970a6a04a&photo_id='+original_photo_id+'&format=json&jsoncallback=?',
    function(data){
		$("#photoThumb").attr("src",data.sizes.size[2].source);
		$("#photoThumb").attr("width",data.sizes.size[2].width);
		$("#photoThumb").attr("height",data.sizes.size[2].height);
		$("#photoWindow .imageThumbDiv1").css("width", data.sizes.size[2].width + 'px');
		$("#photoWindow .imageThumbDiv1").css("height", data.sizes.size[2].height + 'px');
    });
}

var setUserPage = function(nsid) {
    nsid = nsid.replace("@","%40");
    $.getJSON('http://api.flickr.com/services/rest/?method=flickr.people.getInfo&api_key=ebdb8e3596d2cf4c5987023970a6a04a&user_id='+nsid+'&format=json&jsoncallback=?',
    function(data){
	    var url = data.person.profileurl._content;
	    $("#photoUserURL").attr("href", url);
    });
}

var clearPhotoWindow = function() {
	$("#photoWindowContentDiv").css("opacity", 0);
    $("#photoThumb").attr("src","");
    $("#photoThumb").attr("title","");
    $("#photoTitle").html("");
    $("#photoOriginalURL").attr("href","");
    $("#photoTags").html("");
    $("#photoDescription").html("");
    $("#photoUserURL").attr("href","");
    $("#photoUserURL").html("");
	$("#photoDate").html("");
}

var showOriginalPage = function(id) {
    loadingStart();
    $.getJSON('http://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=ebdb8e3596d2cf4c5987023970a6a04a&photo_id='+id+'&format=json&jsoncallback=?',
    function(data){
	loadingStop();
	window.open(data.photo.urls.url[0]._content,'_blank');
  });
}

var makeTags = function(str) {
    if(str!=null) {
	var tags = str.split(",");
	for(var i=0; i<tags.length; i++) {
	    $("#photoTags").append('<li><a href="index.php?content=tag&q=' + encodeURIComponent(tags[i]) + '">'+tags[i]+'</a></li> ');
	}
    }
}




/**
 * Map
 */

var initializeMap = function() {
    var latlng = null;
    var lat = 1;
    var lng = 1;
    if(lat=="" && lng=="") latlng = new google.maps.LatLng(1,1);
    else {
        try {
            latlng = new google.maps.LatLng(lat,lng);
            var myOptions = {
                zoom: 12,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
		scrollwheel: false
            };
            map = new google.maps.Map(document.getElementById("homepageMap"),myOptions);

            var mapMgr = new mapManager();
        } catch(e) {}
    }
}


