/* SVN FILE: $Id: nt.custom.js 1413 2011-11-20 22:36:46Z hnn $ */
/**
* Project Name :  Project Description
*
* @author         $Author: hnn $
* @copyright      $Copyright$
* @version        $Rev: 1413 $
* @lastrevision   $Date: 2011-11-20 23:36:46 +0100 (Sun, 20 Nov 2011) $
* @license        $License$
* @filesource     $URL: svn://svn.txc.se/nojestorget/branches/nt41/assets/javascript/jquery/nt.custom.js $
*/

jQuery.extend({
	postJSON: function( url, data, callback ) {
		return jQuery.post(url, data, callback, "json");
	},

	postJSONASync: function (url, data, callback)
	{
		return $.ajax({
			type: 'POST',
			async: false,
			url: url,
			data: data,
			success: callback,
			dataType: 'json'
		});
	}

});

function recordOutboundLink(link, category, action)
{
	try
	{
		var pageTracker=_gat._getTracker("UA-23643452-1");
		pageTracker._trackEvent(category, action);
//		setTimeout('document.location.href = "' + link.href + '"', 100)
	}
	catch(err)
	{
//		window.console.log(err);
	}

	var url = $(link).attr('href');
	
	setTimeout('window.open(\'' + url + '\')', 100);
}


$(document).ready(function()
{
    $(document).bind("contextmenu",function(e){
        return false;
    });

	// Open links with rel="external" in new window
	$('A[rel~="external"]').click( function()
	{
		var o = $(this);
		var t = o.attr('lt');
		var i = o.attr('lid');

		recordOutboundLink($(this), t, i);
		return false;
	});
/*
	$("#divLoading").bind("ajaxSend", function(){
		$(this).show();
		$('#divSearchInfo').hide();
	}).bind("ajaxComplete", function(){
		$(this).hide();
		$('#divSearchInfo').show();
	});
*/	
	$('.Contact').focus(function () {
		value = $(this).val();
		title = $(this).attr('title');
		if(value == title) {
			$(this).val('').addClass('colBlack').removeClass('colGrey');
		}
	}).blur(function () {
		value = $(this).val();
		title = $(this).attr('title');
		if(value == '') {
			$(this).val(title).addClass('colGrey').removeClass('colBlack');
		}
    });
    
	$('a.newwindow').click(function(e)
	{
		win = window.open($(this).attr('href'));

		if(win==null)
			alert('Please activate popupwindows');
		
		win.focus();
		return false;
	});

	$('.LastMinuteArtist').toggle(function() {
		NT.LMShow($(this).attr('title'));
	}, function() {
		NT.LMHide($(this).attr('title'));
	});

//	$('a.showmp3').colorbox({ inline:true, href:"#mp3player", width:"350px", height:"125px" });
//	$('a.showyoutube').colorbox({ inline:true, href:"#youtube", width:"898px", height:"595px" });
});

function isValidEmailAddress(emailAddress)
{
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
}

var NT = {
	Submit: function (el)
	{
		$(el).submit();
//		return false;
	},
	
	Reset: function (el)
	{
		$(el)[0].reset();
	},

	Ajax: function (el)
	{
		var data = $(el).serialize();
		var url = $(el).attr('action');
		$.postJSON(url, data, function(resp)
		{
			if ( $("#dialog").length > 0 )
			{
				$('#dialog').html(resp.msg);
				$("#dialog").dialog("open");		
			}
			else NT.Popup(resp.msg);
		});
		
		NT.Reset(el);
	},
	
	CheckSearch: function(obj)
	{
		if(obj.value == 'Sök')
			return false;
		
		if(obj.value == 'Sök ditt nöje gratis här')
			return false;
	},

	Call: function (url)
	{
		$.postJSON(url, function(resp)
		{
			if ( $("#dialog").length > 0 )
			{
				$('#dialog').html(resp.msg);
				$("#dialog").dialog("open");		
			}
			else NT.Popup(resp.msg);
		});
	},
	
	Populate: function (obj)
	{
		$('#kat2').hide().html('<option value="0">- Välj Huvudkategori -</option>');
		$('#kat3').hide().html('<option value="0">- Välj Gruppkategori -</option>');

		NT.UpdateAds(obj.val())

		$.postJSON('/rpc.php',{ action: 'categories', cat: obj.val() }, function(jsonData)
		{
			var options = '<option value="0">- Sök Gruppkategori -</option>';

			if(jsonData)
			{
				$.each(jsonData, function(key,object)
				{
					options += '<option value="' + key + '">' + object + '</option>';
				})
				$('#kat2').html(options).show();
			}
		});
	},
	
	PDFDialog: function ()
	{
		$('#pdfdialog').dialog({ width: '350px', height: '200px' });
	},

	PDFMail: function ()
	{
		url = '/PDF.html?action=Email';
		var data = $('#pdfform').serialize();
		
		$.post(url, data, function(transport) {
			$('#pdfdialog').dialog('close');
			$('#pdfmessage').html(transport);
			$('#pdfdialog').dialog('open');
			$('#pdfform')[0].reset()
		});

	},

	SetList: function (value)
	{
		switch(value)
		{
			case 'newsletter':
				$('#ArtistForm').attr('action', 'http://www.meint.se/me3/open/subscribe.jsp');
			break;
			case 'contact':
				$('#ArtistForm').attr('action', '?action=ContactSend');			
			break;
		}
	},

	Search: function (prefix, value)
	{
		$('#catUnder').val(value);

		$('#sp-searchtext').val(prefix + ':' + value)
		
		$("#frmSideSearch").submit();
	},

	customSearch: function (prefix, value)
	{
		$('#catHuvud').val(prefix);
		$('#catGrupp').val(value);
		$('#sp-searchtext').val('grupp:' + value)
		
		$("#frmSearch").submit();
	},
	
	MenuAutoload: function (val)
	{
		NT.Menu(val.huvud);
	},
	
	Menu: function (val)
	{
		$('#sideMenuContent').html('<img src="/assets/images/spinner.gif" />');
		
		$.postJSON('/api/menu',{ action: 'categories', cat: val }, function(jsonData)
		{
			var options = '<ul>';

			if(jsonData)
			{
				$.each(jsonData, function(key,object)
				{
					options += '<li><a href="/Search.html?q=grupp:'+escape(key)+'&huvud='+val+'&grupp='+escape(key)+'">'+object+'</a></li>';
				})
			}
			options += '</ul>';

			$('#sideMenuContent').html(options).show();
		});
		
		$('#sideMenuBtn input').removeClass('backYellow colBlack').addClass('backBlue colWhite');
		$('#btn'+val).removeClass('backBlue colWhite').addClass('backYellow colBlack');
	},
	
	UpdateAds: function (cat)
	{
		$.postJSON('/_lib/adhelper.php',{ cat: cat }, function(jsonData)
		{
			var URL = 'http://www.nojestorget.se/mysimpleads/mysa_output.php?r='+jsonData['ip']+'&h='+escape(jsonData['host'])+'&ua='+escape(jsonData['ua'])+'&rf='+escape(document.referrer)+'&show_ad_group=';
			
			$('#adNTLeft').load(URL + jsonData['adgroup']);
			$('#adNTRight').load(URL + (jsonData['adgroup']+1));
		})
	},
	
	Save: function (lopnr, cookie)
	{
		var ArtistID = isInt(lopnr);
	
		if(ArtistID == 0)
		{
			alert(ArtistID);
			return false;
		}
	
		var url = '/List/add/'+ cookie +'/' + ArtistID;
		$.post(url, function(transport) {
				$('#saveme'+lopnr+'-'+cookie).val(transport).attr('disabled','disabled');
		});
	},
	
	Clean: function (lopnr, cookie)
	{
		if(lopnr != 'wipe')
		{
			var ArtistID = isInt(lopnr);
	
			if(ArtistID == 0)
			{
				alert(ArtistID);
				return false;
			}
		}
		else
			var ArtistID = 'wipe';
	
		var url = '/List/remove/'+ cookie +'/' + ArtistID;
		$.post(url, function(transport) {
				$('#SaveTotal').html(transport+' st');
				$('#saveme'+ArtistID+'-'+cookie).hide('slow');
		});
	},
	
	Popup: function (msg, title)
	{
		if(isNaN(title))
			title = 'Meddelande';

		$("body").after('<div id="dialog">'+msg+'</div>');
		$("#dialog").dialog("destroy");
		$("#dialog").dialog({
			modal: true,
			autoOpen: false,
			title: title,
			width: 600,
			position: 'top',
			buttons: { Ok: function() { $(this).dialog('close'); } }
		});
		$("#dialog").dialog("open");
	},

	Modal: function (value)
	{
		$("body").after('<div id="dialog"></div>');
		$("#dialog").dialog("destroy");
		$("#dialog").dialog({
			modal: true,
			autoOpen: false,
			width: 600,
			minWidth: 400,
			maxWidth: 600,
			position: 'top'
		});
		$("#dialog").load(value, function(resp) {
			$(this).html(resp);
			var $text = $('#dialog h1:first');
			$text.hide();
			$("#dialog").dialog('option', 'title', $text.text())
			$("#dialog").dialog("open");
		});
    },
    
    WrongInfo: function ()
    {
    	info = $('#WIinfo').val();

    	msg = "";
    	
		if($('#WIinfo').val() == $('#WIinfo').attr('title'))
			msg += 'Vänligen fyll i ett korrekt meddelande!\n';

		if($('#WIlist').val() == 0)
			msg += 'Vänligen välj ditt namn i listan!\n';

    	if(info.length < 10)
    		msg += 'Meddelandet är för kort, skriv så utförligt du kan för att underlätta att rätt information kan visas!\n';
		
		if(msg == "")
		{
			$('#WIsubmit').attr('disabled','disabled');
			NT.Submit('#WrongInfo');
		}
		else
			alert(msg);
    },
    
    LMShow: function (date)
    {
		$('#layer'+date).html('<img src="/assets/images/spinner.gif" />').show('slow');
		$(this).click(function() { NT.LMHide(date); });
		$('#d' + date).addClass('selected');

		var html = '';

		$.getJSON('/api/lmartists/'+date, function(items)
		{
			html += ' ';

			$.each(items, function(k,i)
			{
				var image = '';
				if(i.image != 0 || i.image != '') {
					image = unescape(i.image);
				}

				var sharethis = '';
				sharethis += 'st_title=\'' + unescape(i.name) + ' på Nöjestorget\'';
				sharethis += 'st_image=\'' + image + '\'';
				sharethis += 'st_title=\'' + unescape(i.name) + ' på Nöjestorget\'';
				
			
				html += '<div class="postMain" style="float:left; width:100%;">';
				html += '<a name="s' + i.date + '-' + i.id + '"></a>';
		
				html += '<div class="postPicture" style="margin-top: 5px; height:125px;">';
				html += '<a href="' + unescape(i.url) + '">' + image + '</a><br />';
				html += '<a href="' + unescape(i.url) + '" style="color:#E8F0DE; width:75%;" class="button green small">Läs mer</a>';
				html += '<div class="clear"></div>';
				html += '</div>';

				html += '<div class="postContainer">';
				html += '<div class="postContent">';
				html += '<a href="' + unescape(i.url) + '"><h2>' + unescape(i.name) + '</h2></a>';

				html += '<div class="postButton" style="margin-top: 3px;">';
				
//				html += '<input type="button" class="button green small" onclick="go(\'/pContact.html?noje=' + i.lopnr + '\');" value="Kontakta" />';

				html += '<div style="margin-top: 5px;">';
				html += '<span class=\'st_twitter_button\' displayText=\'\' ' + i.sharethis + '></span>';
				html += '<span class=\'st_facebook_button\' displayText=\'\' ' + i.sharethis + '></span>';
				html += '<span class=\'st_email_button\' displayText=\'E-post\' ' + i.sharethis + '></span>';
				html += '</div>';
				html += '</div>';

				html += '<span class="verdana center size11 bold">' + i.lopnr + '</span><br/>';
				html += '<span class="verdana size11 colBlack">' + i.tags + '</span><br/>';
				html += '<span class="verdana size11 colBlack">' + unescape(i.description) + '<br/>';
				html += unescape(i.contact);
				html += '</span>';

				if(i.admin != '') {
					html += '<div style="float:right;">';
					html += unescape(i.admin);
					html += '</div>';
				}

				html += '</div></div></div>';
				html += '<div class="clear"></div>';
			});
	
			$('#layer'+date).html(html);
			stButtons.locateElements();
		});

    },
    
    LMHide: function (date)
    {
		$('#d' + date).removeClass('selected');
		$('#layer'+date).hide('slow');
		$(this).click(function() { NT.LMShow(date); });

    }
};

var FN = {
	Show: function (name)
	{
		$.getJSON('/fantastiskanojen/personer/'+name, function(items)
		{
			html = '<div id="divPresentation" style="text-align: center; height: 210px;">';
			
			html += '<div id="divPresText" class="center" style="float: right; width:285px;margin-left:10px;">';
			html += '<div id="scrollme" class="verdana size10 left" style="overflow: auto; padding:3px; width: 304px; height:204px;">';
			html += '<h4>'+items.name+'</h4><span class="verdana size12 bold colBlack">'+items.company+'</span><br /><span class="verdana size11 colBlack">'+items.title+'</span><p style="width:90%;">'+items.content+'</p><p><a href="mailto:'+items.email+'" class="size12">'+items.email+'</a><br/>'+items.phone+'</p></div>';
			html += '</div>';
			
			html += '<div id="divPresImage" style="width: 340px; float: left; text-align: left; margin-left:15px;">';
			
			if(items.image != 0 || items.image != '')
				html += '<img src="'+items.image+'" style="'+items.style+'" width="340" height="210" alt="'+items.name+'" />';

			html += '</div></div>';
	
			$('#FN'+name).hide('slow');
			$('#NT'+name).html(html).show('slow');
		});
	},
	
	Hide: function (name)
	{
		$('#NT'+name).hide('slow');
		$('#FN'+name).show('slow');
	}
}

function showProp(obj)
{
	str='';
	for(prop in obj)
	{
		str+=prop + " : "+ obj[prop]+"\n";
	}
	return(str);
}

function ucword(str)
{
	var tmpStr, tmpChar, preString, postString, strlen;
	tmpStr = str.toLowerCase();
	stringLen = tmpStr.length;
	if (stringLen > 0)
	{
		for (i = 0; i < stringLen; i++)
		{
			if (i == 0)
			{
				tmpChar = tmpStr.substring(0,1).toUpperCase();
				postString = tmpStr.substring(1,stringLen);
				tmpStr = tmpChar + postString;
			}
			else
			{
				tmpChar = tmpStr.substring(i,i+1);
				if (tmpChar == " " && i < (stringLen-1))
				{
					tmpChar = tmpStr.substring(i+1,i+2).toUpperCase();
					preString = tmpStr.substring(0,i+1);
					postString = tmpStr.substring(i+2,stringLen);
					tmpStr = preString + tmpChar + postString;
				}
			}
		}
	}
	return tmpStr;
}
