// Identify and store the current domain name
re = new RegExp("http://[^\/]+")

currentDomain = new String(window.location)
currentDomain = currentDomain.match(re)[0]

// Show any Google Maps map initialized with maps.showAddres(map_canvas, address, title, url)

maps =
{
	addressQueue : [],
	isReady : false,
	showAddress : function(map_canvas, address, title, url) { 
					var mapInfo = { map_canvas : map_canvas, address : address, title : title, url : url }
					maps.addressQueue.push(mapInfo)
					if(maps.isReady)
						maps.showMaps()
				},

	geocoder : null,

	initialize : function(mapInfo) {
	  if(mapInfo.map)
		return
 
	  //if (GBrowserIsCompatible()) {
		latlng = new google.maps.LatLng(50.0878114, 14.4204598);
		maps.options = {
			zoom : 13,
			center : latlng,
			mapTypeId : google.maps.MapTypeId.ROADMAP
		}

		maps.geocoder = new google.maps.Geocoder();

		mapInfo.map = new google.maps.Map(document.getElementById(mapInfo.map_canvas), maps.options);
	  //}
	},

	_showAddress : function (mapInfo){
	  if (maps.geocoder) {
		maps.geocoder.geocode(
			{ 'address' : mapInfo.address },
			function(results, status) {
				if (status == google.maps.GeocoderStatus.OK) {
					mapInfo.map.setCenter(results[0].geometry.location);
					var marker = new google.maps.Marker(
						{
							map : mapInfo.map,
							position : results[0].geometry.location,
							title : "title!" //"<b><u><a href='" + mapInfo.url + "'>" + mapInfo.title + "</a></u></b><br>" + mapInfo.address
						}
					)
					
					var infowindow = new google.maps.InfoWindow({
						content: "<b><u><a href='" + mapInfo.url + "'>" + mapInfo.title + "</a></u></b><br>" + mapInfo.address
					});
						
					infowindow.open(mapInfo.map,marker);
					
					marker.setVisible(true)
					console.log(marker)
				}
				else
				{
					alert("Google Maps: Адрес не найден по следующей причине: " + status);
				}
			}
		)
	  }
	},
	
	showMaps : function()
	{
		maps.isReady = true
		
		for(i = 0; i < maps.addressQueue.length; i++)
		{
			mapInfo = maps.addressQueue[i]
			maps.initialize(mapInfo)
			maps._showAddress(mapInfo)
		}	
	}
}


args = "Aaa"
// ---------------------
// Comments autorefresh
// ---------------------

function formatDate(isodatestring)
{
	isodate = isodatestring
	yr = isodate.substr(2,2)
	mo = isodate.substr(5,2)
	dy = isodate.substr(8,2)
	hr = isodate.substr(11,2)
	mn = isodate.substr(14,2)
	return dy + "." + mo + "." + yr + " " + hr + ":" + mn
}

received_comments = []
comments_update_frequency_seconds = 15
comments_timer_handler = -1
skip_comments_update = 0


function updateComments(response)
{
	document.response = response
	
	document.last_requested = new Date(response['server_datetime'])
	console.log(response['server_datetime'])
	var comments
	if('comments' in response)
		comments = response['comments']
	else
		return
	
	// The following prevents a "racing condition" when adding (deleting?) comments
	if (document.last_requested != document.last_received)
		document.last_received = new Date(response['server_datetime'])
	else
		return
	
	commentsTemplate = $(".commentTemplate")
	for (i=0; i < comments.length; i++)
	{
		var c = comments[i]
		
		c_id = c["id"]
		if($.inArray(c_id, received_comments) > -1)
			continue

		received_comments.push(c_id)

		var newComment = commentsTemplate.clone().removeClass("commentTemplate")
		newComment.find(".commentContent").html(c["content"])
		newComment.find(".pubDate").html(formatDate(c["pub_date"]))

		// userlink
		userlink = newComment.find(".userlink")
		userlink.attr("href", c["user_url"])
		userlink.html(c["user_first_name"] + " " + c["user_last_name"])

		// delete comment button	
		removeCommentSpan = newComment.find(".deleteButton")
		removeComment = removeCommentSpan.find("a")
		if(!c["can_edit"])
			removeComment.hide()
		else
		{
			removeComment.attr("href", c["url"] + "/delete")
			removeComment.click(deleteCommentAJAX)
		}
			//alert(c["url"])

		newComment.find(".photo").attr("src", c["photo_url"])
		
		$("#comments").prepend(newComment)
		newComment.fadeIn("1500")
	
		//newComment.css("border" : "1px solid black")

	}
}


function setDiscussionThreadId(threadid, baseObjectType, baseObjectId)
{
	if(!threadid)
		threadid = "_"

	document.discussion_threadid = threadid
	document.discussion_baseObjectType = baseObjectType || ""
	document.discussion_baseObjectId = baseObjectId || ""
}

function pad0(n)
{
	 return (n < 10) ? "0" + n : "" + n
}

function lastCommentsAJAX(scheduledCall)
{
	if(!document.last_requested)
		return
	
	
	
	scheduledCall = !(typeof(scheduledCall) === 'undefined')
	// IF this is a non-scheduled call, skip the next scheduled one
	if(scheduledCall && !!document.skipNextScheduledCall)
	{
		
		document.skipNextScheduledCall = false
		return
	}
	
	document.skipNextScheduledCall = !scheduledCall
	
	lr = document.last_requested

	h = pad0(lr.getHours()) // Take care during DST changes!
	m = pad0(lr.getMinutes())
	s = pad0(lr.getSeconds())

	lr = h+m+s
	
    if(document.discussion_threadid && (lr.length == 6))
        $.ajax(
                {
                    url : currentDomain + "/discussions/t/" + document.discussion_threadid + "/slug/lastCommentsAJAX/" + lr,
                    dataType : "json",
                    success : updateComments
                }
            )
}

function addCommentAJAX()
{
	var tb_content = $('textarea#id_content')

	tb_content.attr('disabled', true);
	$(".commentPostForm #submit").attr('disabled', true);

	var content = tb_content.val()

	// alert(document.discussion_threadid)

	var baseObj = document.discussion_baseObjectType && (document.discussion_baseObjectType + "/" + document.discussion_baseObjectId)

	$.ajax(
			{
				url : currentDomain + "/discussions/t/" + document.discussion_threadid + "/slug/addCommentAJAX/" + baseObj,
				type : "POST",
				data : {"content" : content},
				success : function(result)  // Result will contain thread id
				{
					if(document.discussion_threadid == "_")
						document.discussion_threadid = result

					tb_content.val("");
					tb_content.attr('disabled', false);
					$(".commentPostForm #submit").attr('disabled', false);
					lastCommentsAJAX()
				}
			}
		)
}

function deleteCommentAJAX()
{
	//var dialog = $('<div id="dialog-confirm" title="Точно удалить?"><p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>Комментарий будет удален навсегда! Точно продолжить?</p></div>');
	//$(document).append(dialog)
	console.log($(this))
	document.bubu = this
	var reply = confirm("Точно удалить?", $(this).attr("href"))
	
	if (!reply) return false
	
	el = $(this)
	url = el.attr("href")

	$.ajax(
                {
                    url : url,
                    dataType : "json",
                    success : function(r) { if(!r['value']) $(el.parents()[2]).fadeOut(); else alert("Комментарий не был стерт!") }
                }
            )
			
	return false
}

$().ready(
	function ()
	{
		$(".commentPostForm #submit").click(function(o) { addCommentAJAX(); return false})
		//$(".commentDiv .deleteButton").click(function(
		
		if(server_datetime && $(".commentPostForm #submit"))
		{
			document.last_requested = server_datetime
			setInterval(lastCommentsAJAX, comments_update_frequency_seconds*1000)
		}
		//if($(".commentPostForm #submit"))
		//{	
			//lastCommentsAJAX()
		
		//}
		
		// Set up delete buttons
		
		$('span.deleteButton a').click(deleteCommentAJAX)
		
		//.find('a').attr("href")
	}
)


// -------------------------
// End Comments autorefresh
// -------------------------

// -------------------------
// Auto slug
// -------------------------

cyr = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя ".split("")
lat = "a,b,v,g,d,e,е,zh,z,i,j,k,l,m,n,o,p,r,s,t,u,f,h,c,ch,sh,sh,,y,,e,ju,ja,-".split(",")
var latre=/^[A-Za-z\-_0-9]{1}$/

cyr2lat_map = new Object
for(i=0; i < cyr.length; i++)
        cyr2lat_map[cyr[i]] = lat[i]

function cyr2lat(s)
{
    t = []
    s = s.toLowerCase()
    for(i=0; i < s.length; i++)
        if(latre.test(s[i]))
            t[i] = s[i]
        else
            t[i] = cyr2lat_map[s[i]]

    return t.join("")
}

$().ready(
	function()
	{
		$(".slug_source input").eq(0).change(function(){
			if($(".slug_target input").eq(0).val())
				return
				
			slug = cyr2lat($(".slug_source input").val())
			
			if(slug.length >= 50)
				slug = slug.substring(0,50)

			$(".slug_target input").eq(0).val(slug)
		})
	}
)

// -------------------------
// End Auto slug
// -------------------------

function setupDateInputs(){
			//date_formfield = $('#id_{{ profile_form.birthdate.name }}')

			datetimeinputs = $(".datetimeinput input")
			dateinputs = $(".dateinput input")
			
			if(datetimeinputs.length)
			{

				$.datepicker.setDefaults($.datepicker.regional['ru']);
				
				for(i = 0; i < datetimeinputs.length; i++)	
				{
					di = $(datetimeinputs[i])
					dtp = di.datetimepicker({dateFormat: "yy-mm-dd", defaultDate: di.val()})
					di.change(function(){
					  v = $(this).val()
					  var dt, hr
					  arr = v.split(" ")
					  dt = arr[0]
					  hr = arr[1]
					  hr = hr.split(":")
					  
					  v = dt+" "+hr.join(":")

					  if(hr.length < 3)
						v += ":00"

					  $(this).val(v)
					})
				}
					
				$("#locale").change(function() {
										$('#datepicker').datetimepicker('option', $.extend({showMonthAfterYear: false}, $.datepicker.regional[$(this).val()]));
									});
			}

			if(dateinputs.length)
			{
				for(i = 0; i < dateinputs.length; i++)
					di = $(dateinputs[i])
					dp = di.datepicker({dateFormat: "yy-mm-dd", defaultDate: di.val()})
			}
								
		}
		
function doRotateItems(itemsAnchor, timeOut, totalItems, callback) // Callback will be called on cloned elements, first use is prettyPhoto
{
	all = $(itemsAnchor)
	
	if(!totalItems)
		totalItems = all.length || -1

	if((all.length != totalItems) || (totalItems < 0))
		return // Stop rotation

	last = all[all.length-1]
	first = all[0]
	firstClone = $(first).clone()
	$(firstClone).hide()
	$(last).after(firstClone)
	
	first = all[0]

	$(first).slideUp(1000, function() { $(first).remove(); } )	
	$(firstClone).slideDown(1000);
	//$(firstClone).slideDown(1500)
	setTimeout(function(){doRotateItems(itemsAnchor, timeOut, totalItems)}, timeOut*1000)
}

function rotateItems(itemsAnchor, timeOut)
{
	$(document).ready(function(){
		setTimeout(function(){doRotateItems(itemsAnchor, timeOut)}, timeOut*1000)
	})
}
		
//$().ready(function(){
//})

function trackExternalLikns()
{
	if(typeof(pageTracker) != "undefined")
		$("a[href^='http://']").click(
			function ()
			{
				pageTracker._trackPageview('/exit/'+ $(this).attr('href'));
				console.log("tracked " + $(this).attr('href'))
			}
		)
}

$(document).ready(function(){

	trackExternalLikns()
	
	setupDateInputs()

	maps.showMaps()

   // PrettyPhoto Setup
   pf = $("a[rel^='prettyPhoto']")

   for(var i = 0; i < pf.length; i++)
   {
		p = $(pf[i])
		p.attr("photopage_href", p.attr("href"))
		p.attr("href", p.attr("pp_href"))
	}
	
   if(pf.length)
	pf.prettyPhoto(
		{
			overlay_gallery : true,
			//changepicturecallback : function(t) { document.trigger = this }
		}
	);
	
	// Configure photo delete checkboxes
	pdcb = $(".photo_delete_cb")
	pdcb.click(function(ev){ ev.stopPropagation() })
	trigger_all_photo_delete_cb = $(".toggle_all_photo")
	trigger_all_photo_delete_cb.click(function() {pdcb.prop("checked", trigger_all_photo_delete_cb.prop("checked")); } )

});

/*$().ready(
	function initExpandableText()
	{
		expandables = $(".expandableText")
		alert(expandables[0])
	}
)*/
