if (window.location.hash != '')
{
	var hash = window.location.hash;
	if (hash != '')
		window.location.href = hash.substring(1,hash.length);
	
}

if (typeof console === undefined)
	console = {log: function() {}};

Inv = {
	check: function(yahooid)
	{
		Nid.show(Nid.baseUrl + '/check/' + yahooid, {target: '.' + yahooid.replace(/[@.]/g, '-') + '-status', scroll: false, loading: '<img src="' + Nid.baseUrl + '/img/icons/loading.gif" alt="loading" class="icon" /> Checking...'});
	},
	checkLite: function(yahooid)
	{
		Nid.show(Nid.baseUrl + '/checklite/' + yahooid, {target: 'checkResult', scroll: false, loading: '<img src="' + Nid.baseUrl + '/img/icons/loading.gif" alt="loading" class="icon" /> Checking...'});
	},	
	report: function(type, id, yahooid)
	{
		if (!confirm('Are you sure you want to report this image to Invisipolice?'))
			return;
		
		if (type == 'displayimage')
			Nid.show(Nid.baseUrl + '/yahoo/report/displayimageid/' + id, {target: '.displayimage-' + id, scroll: false, loading: ' '});
		else if (type == 'yahooid')
			Nid.show(Nid.baseUrl + '/yahoo/report/yahooid/' + id, {target: '.yahooid-' + yahooid, scroll: false, loading: ' '});
	},
	menu:
	{
		timer: ''
		,hideSubmenus: function() {
			$('.menu .trigger').parent().removeClass('selected');
		}
		,init: function() {
			$('.menu .trigger').click(
				function() { 
					$(this).parent().toggleClass('selected');
				});

			$('.menu .submenu').mouseover(function() {
				clearTimeout(Inv.menu.timer);
			});
			$('.menu .trigger').mouseover(function() {
				clearTimeout(Inv.menu.timer);
			});

			$('.menu .trigger').mouseout(function() {
				Inv.menu.timer = setTimeout("Inv.menu.hideSubmenus()",300);	
			});

			$('.menu .submenu').mouseout(function() {
				Inv.menu.timer = setTimeout("Inv.menu.hideSubmenus()",300);	
			});

		}
	}	
};


Inv.map = {
		
	addMarkers: function(map, positions)
	{
		var position;
		for (var i = 0; i < positions.length; i++)
		{
			position = positions[i];
			var marker = new google.maps.Marker({
		        position: new google.maps.LatLng(position.lat, position.lng), 
		        map: map,
		        icon: Nid.baseUrl + '/img/icons/marker.png',
		        title: position.title
		    });
		}
	}	
}

function search(action, params)
{
	postObject = new Object;
	postObject.ajax = 'true';
	postObject.breadcrumb = 'false';
	postObject.query = params['query'];
	return $.ajax({
        type: "POST",
        url: action,
        data: postObject,
        success: function(data) {
			$('#' + target).html(data);
        },
        error: function (e)
        {
        	window.location.href = action;
        }
    });


    return false;
	
}

function changeGridPage(action, prefix)
{
	if (typeof prefix === undefined)
		prefix = '';
		
	$('#' + prefix + 'gridloading').show();
	//Nid.mask.show(prefix + 'grid');
	postObject = new Object;
	postObject.ajax = 'true';
	return $.ajax({
        type: "GET",
        url: action,
        success: function(data) {
			$('#' + prefix + 'body').html(data);
			$('#' + prefix + 'gridloading').hide();
			//Nid.mask.hide(prefix + 'grid');
        },
        error: function (e)
        {
        	window.location.href = action;
			$('#' + prefix + 'gridloading').hide();
			//Nid.mask.hide(prefix + 'grid');			
        }
    });
}

function changeGridOrder(action, prefix)
{
	if (typeof prefix === undefined)
		prefix = '';
		
	$('#' + prefix + 'gridloading').show();
	postObject = new Object;
	postObject.ajax = 'true';
	return $.ajax({
        type: "GET",
        url: action,
        success: function(data) {
			$('#' + prefix + 'grid').html(data);
			$('#' + prefix + 'gridloading').hide();
		},
        error: function (e)
        {
        	window.location.href = action;
			$('#' + prefix + 'gridloading').hide();
        }
    });
}


Nid.updateInPlace = function(url, column, type)
{
	$('#' + column).editable({
							editBy: 'dblclick',
							type: type,
							onEdit: function(content)
							{
								$('#' + column + ' input').select();
							},
							onSubmit: function(content) {
								if (content.current == content.previous)
									return;
								
								postObject = new Object;
								postObject.column = column;
								postObject.value = content.current;
								$.post(url, postObject, function(obj){
									if (obj.status != "success")
									{
						    			$('#' + column).html(content.previous);
						    			if (obj.message)
						    				$.dialog.showAlert(obj.message, 'error', obj.title);
									}
									else
									{
						    			if (obj.message)
						    				$.dialog.showAlert(obj.message, 'info', obj.title);
										
									}
							    }, "json");
							}
						});
}




Nid.get = function(action, params)
{
	var target = params['target'];
	if (target.substring(0,1) != '.' && target.substring(0,1) != '#')
		target = '#' + target;
	
	if (params['mask'])
		Nid.mask.show(params['mask']);
	else
	{
		if (params['loading'])
			$(target).html(params['loading']);
		else
			$(target).html('Please wait');
	}
	
	postObject = new Object;
	postObject.ajax = 'true';
	postObject.breadcrumb = params['breadcrumb'];
	
    return $.ajax({
        type: "POST",
        url: action,
        data: postObject,
        success: function(data) {
			$(target).html(data);
			$(target).scrollTo(300);
			
						
			if (params['target'] == 'container')
				window.location.hash = action;
			
			if (params['mask'])
				Nid.mask.hide(params['mask']);			
        },
        error: function (e)
        {
        	window.location.href = action;
        	
        	if (params['mask'])
        		Nid.mask.hide(params['mask']);        	
        }
    });

    return false;
	
};


Nid.show = function(action, params)
{
	if (params['scroll'] === undefined)
		params['scroll'] = false;

	var target = params['target'];
	if (target.substring(0,1) != '.' && target.substring(0,1) != '#')
		target = '#' + target;
	
	
	if (params['mask'])
		Nid.mask.show(params['mask']);
	else
	{
		if (params['loading'])
			$(target).html(params['loading']);
		else
			$(target).html('Please wait');
	}
	
	postObject = new Object;
	postObject.ajax = 'true';

    return $.post(action, postObject, 
        function(obj) {
    		if (obj.status == "success") {
    			if (obj.hideDialog)
    				$.dialog.hide();
    			if (obj.submitForm)
    				$('#' + obj.submitForm).submit();
    			
    			if (obj.result)
    			{
    				if (obj.target)
    				{
    					target = obj.target;
    					if (target.substring(0,1) != '.' && target.substring(0,1) != '#')
    						target = '#' . target;
    				}
    				
    				if (obj.resultAddType == 'append')
    					$(target).append(obj.result);
    				else if (obj.resultAddType == 'prepend')
    					$(target).prepend(obj.result);
    				else
    					$(target).html(obj.result);
    				
					if (params['scroll'])
						$(target).scrollTo(300);
				
					if (target == '#container')
						window.location.hash = action;
    			}
    			
    			if (obj.message && obj.title)
    			{
    				if (obj.noicon)
    					$.dialog.showAlert(obj.message, 'noicon', obj.title);
    				else
    					$.dialog.showAlert(obj.message, 'info', obj.title);
    			}

				if (obj.redirect)
					window.location.href = obj.redirect;
				
				
    		} else {
    			if (obj.result)
    				$(target).html(obj.result);
    			
    			if (obj.message)
					$.dialog.showAlert(obj.message, 'error', obj.title);
    			else {
					$.dialog.showAlert(obj, 'error', obj.title);
	            	window.location.href = action;
    			}
    		}
    		
			if (params['mask'])
				Nid.mask.hide(params['mask']);
        }
    , "json");


    return false;
	
};

Nid.mask = {
	show: function(target) 
	{
		if (target.substring(0,1) != '.' && target.substring(0,1) != '#')
			target = '#' + target;
		$(target).addClass('masked');
		if ($(target + '-mask').length)
		{
			$(target + '-mask').removeClass('hidden');
		}
		else
			$(target).append('<div id="' + target.substring(1) + '-mask" class="mask"></div>');
	},
	hide: function(target)
	{
		if (target.substring(0,1) != '.' && target.substring(0,1) != '#')
			target = '#' + target;
		$(target + '-mask').addClass('hidden');
	}
};


Nid.chat = {};

Nid.chat = {
		options: [],
		conferenceUsers: [],
		maskFrame: 'chatroom',
		retryCount: 0,
		setupCon: function(con)
		{
			con.registerHandler('message',Nid.chat.handleMessage);
			con.registerHandler('presence',Nid.chat.handlePresence);
			con.registerHandler('iq',Nid.chat.handleIQ);
			con.registerHandler('onconnect',Nid.chat.handleConnected);
			con.registerHandler('onerror',Nid.chat.handleError);
			con.registerHandler('status_changed',Nid.chat.handleStatusChanged);
			con.registerHandler('ondisconnect',Nid.chat.handleDisconnected);
			
			con.registerIQGet('query', NS_VERSION, Nid.chat.handleIqVersion);
			con.registerIQGet('query', NS_TIME, Nid.chat.handleIqTime);
		},
		init: function(options) {
		  try {
			Nid.chat.conferenceUsers = [];
			Nid.chat.options = options;
			
		    oArgs = new Object();
		    oArgs.httpbase = Nid.chat.options.server;
		    oArgs.timerval = 2000;

		    Nid.chat.con = new ChatHttpBindingConnection(oArgs);

		    Nid.chat.setupCon(Nid.chat.con);

		    oArgs = {
		    		domain: Nid.chat.options.domain,
		    		username: Nid.chat.options.username,
		    		resource: 'SMChatJS',
		    		pass: 'invisible.ir',
		    		register: false,
		    		authtype: 'nonsasl'
		    };
		    
		    Nid.chat.retryCount += 1;
		    
			Nid.chat.args = oArgs;
			Nid.chat.con.connect(oArgs);
		  } catch (e) {
		    ////console.log(e.toString());
		  } finally {
		    return false;
		  }
		},
		addSecurity: function(packet)
		{
			packet.getNode().setAttribute('username', Nid.chat.options.username);
			packet.getNode().setAttribute('date', Nid.chat.options.date);
			packet.getNode().setAttribute('key', Nid.chat.options.key);
			return packet;
		},
		sendMsg: function(sendTo, message) {
			  if (sendTo == '' || message == '')
			    return false;

			  if (sendTo.indexOf('@') == -1)
			    sendTo += '@' + Nid.chat.con.domain;
				
			  try {
			    var aMsg = new ChatMessage();
			    aMsg = Nid.chat.addSecurity(aMsg);
			    aMsg.setTo(new ChatJID(sendTo));
			    aMsg.setBody(message);
			    Nid.chat.con.send(aMsg);
			    return false;
			  } catch (e) {
			    ////console.log("<div class='msg error''>Error: "+e.message+"</div>"); 
			    return false;
			  }
		},
		sendConfMsg: function(conference, message)
		{
		  if (conference == '' || message == '')
			    return false;

		  try {
		    var aMsg = new ChatMessage();
		    aMsg.setTo(new ChatJID(conference + '@conference.' + Nid.chat.con.domain));
		    aMsg.setType('groupchat');
		    aMsg.setBody(message);
		    aMsg = Nid.chat.addSecurity(aMsg);
		    Nid.chat.con.send(aMsg);
		  } catch (e) {
		    ////console.log("<div class='msg error''>Error: "+ e.message +"</div>");
		  }
		},
		logout: function() {
			  var p = new ChatPresence();
			  p.setType("unavailable");
			  Nid.chat.con.send(p);
			  Nid.chat.con.disconnect();
			  
			  //////console.log('Logged out');
		},


		/** Handlers! **/
		handleIQ: function(aIQ) {
			  document.getElementById(Nid.chat.options.target).innerHTML = 
			    "<div class='msg'>Err: " +aIQ.xml().htmlEnc() + '</div>' + document.getElementById(Nid.chat.options.target).innerHTML;
			  Nid.chat.con.send(aIQ.errorReply(ERR_FEATURE_NOT_IMPLEMENTED));
		},
		handleMessage: function(aChatPacket) {
			  var html = '';
			  var username = aChatPacket.getFromJID().getResource();
			  html += '<div class="msg"><b><a target="_blank" href="' + Nid.baseUrl + '/' + username + '/">' + username +'</a>:</b><br/>';
			  html += aChatPacket.getBody().htmlEnc() + '</div>';
			  document.getElementById(Nid.chat.options.target).innerHTML = html + document.getElementById(Nid.chat.options.target).innerHTML;
		},
		handlePresence: function(aChatPacket) {
			  var html = '<div class="msg">';
			  if (!aChatPacket.getType() && !aChatPacket.getShow()) 
			  {
			    html += '<b>'+aChatPacket.getFromJID().getResource() +' joined the room.</b>';
			    Nid.chat.conferenceUsers.push(aChatPacket.getFromJID().getResource());
			  }
			  else {
				
//			    html += '<b>'+aChatPacket.getFromJID()+' is ';
//			    if (aChatPacket.getType())
//			      html += aChatPacket.getType() + '.</b>';
//			    else
//			      html += aChatPacket.getShow() + '.</b>';
			    
			    if (aChatPacket.getType() == "unavailable")
			    {
				    html += '<b>'+aChatPacket.getFromJID().getResource() +' left the room.</b>';
			    	for (var i = 0; i < Nid.chat.conferenceUsers.length; i++) {
			    	if (Nid.chat.conferenceUsers[i] == aChatPacket.getFromJID().getResource())
			    		Nid.chat.conferenceUsers.splice(i, 1);
			    	}			    	
			    }

			    if (aChatPacket.getStatus())
			      html += ' ('+aChatPacket.getStatus().htmlEnc()+')';
			  }
			  html += '</div>';
			  Nid.chat.renderUserlist();
			  document.getElementById(Nid.chat.options.target).innerHTML = html + document.getElementById(Nid.chat.options.target).innerHTML;
		},
		handleError: function(e) {
			  ////console.log("An error occured:<br />"+ 
//			    ("Code: "+e.getAttribute('code')+"\nType: "+e.getAttribute('type')+
//			    "\nCondition: "+e.firstChild.nodeName).htmlEnc()); 

			  if (Nid.chat.con.connected())
			    Nid.chat.con.disconnect();
			  if (e.getAttribute('code') == 401 && Nid.chat.args.register != true)
			  {
				Nid.chat.args.register = true;  
				Nid.chat.con.connect(Nid.chat.args);
			  }

		},
		handleStatusChanged: function(status) {
		  ////console.log("status changed: "+status);
		},
		handleConnected: function() {
			////console.log('NidChat: Connected');

			aPresence = new ChatPresence();
			aPresence = Nid.chat.addSecurity(aPresence);
			Nid.chat.con.send(aPresence);
			Nid.chat.joinConference(Nid.chat.options.conference);
			
		},
		handleDisconnected: function() {
			////console.log('NidChat: Disconnected');
			Nid.mask.show(Nid.chat.maskFrame);
			
			if (Nid.chat.retryCount <= 5)	
			{
//				Nid.chat.init(Nid.chat.options);
			}
				
		},
		handleIqVersion: function(iq) {
			  Nid.chat.con.send(iq.reply([
			                     iq.buildNode('name', 'NidClient'),
			                     iq.buildNode('version', '1.0.0'),
			                     iq.buildNode('os', navigator.userAgent)
			                     ]));
			  return true;
		},
		handleIqTime: function(iq) {
			  var now = new Date();
			  Nid.chat.con.send(iq.reply([iq.buildNode('display',
			                                  now.toLocaleString()),
			                     iq.buildNode('utc',
			                                  now.jabberDate()),
			                     iq.buildNode('tz',
			                                  now.toLocaleString().substring(now.toLocaleString().lastIndexOf(' ')+1))
			                     ]));
			  return true;
		},
		joinConference: function(conference) {
			var packet = new ChatPresence();
			packet.setTo(conference + '@conference.' + Nid.chat.con.domain + '/' + Nid.chat.con.username);
			packet.appendNode('x', {xmlns: "http://jabber.org/protocol/muc"});
			Nid.chat.con.send(packet);
			Nid.mask.hide(Nid.chat.maskFrame);
		},
		renderUserlist: function()
		{
			Nid.chat.conferenceUsers.sort();
			var list = '';
			for (var i = 0; i < Nid.chat.conferenceUsers.length; i++)
			{
				if (Nid.chat.conferenceUsers[i].substr(0,9) == 'anonymous')
					list += '<li>' + Nid.chat.conferenceUsers[i] + '</li>';
				else
					list += '<li><a target="_blank" href="' + Nid.baseUrl + '/' + Nid.chat.conferenceUsers[i] + '">' + Nid.chat.conferenceUsers[i] + '</a></li>';
			}
			document.getElementById(Nid.chat.options.userlist).innerHTML = list;
		}
	};


function rate(url, updateDiv)
{
	$.post(url, {"ajax": "true"}, function(obj){
		if (obj.status == "success")
		{
			$.dialog.showAlert(obj.message, 'info', obj.title);
			$('#' + updateDiv).html(obj.newval);
		}
		else
			$.dialog.showAlert(obj.message, 'error', obj.title);
		
	}, "json");
	
}


(function($){
	$.dialog = function(content) {	
		  $.dialog.showDialog(content);
	};

  $.extend($.dialog, {
	  dialogHtml  : '\
        <div dir="ltr" id="dialog" class="dialog" style="display: none;"> \
          <div class="popup"> \
            <table> \
              <tbody> \
                <tr> \
                  <td class="tl"/><td class="b"/><td class="tr"/> \
                </tr> \
                <tr> \
                  <td class="b"/> \
                  <td class="body"> \
                    <div class="main"> \
                    </div> \
                    <div class="footer"> \
                    </div> \
                  </td> \
                  <td class="b"/> \
                </tr> \
                <tr> \
                  <td class="bl"/><td class="b"/><td class="br"/> \
                </tr> \
              </tbody> \
            </table> \
          </div> \
        </div>',
  		isInit : false,
		initDialog : function()
		{
		     $('body').append($.dialog.dialogHtml);
		
		},
		show : function(data)
		{		
			if (data.ajax)
			{
				postObject = new Object;
				postObject.ajax = 'true';
				postObject.breadcrumb = 'false';
			    $.post(data.ajax, postObject, 
			            function(data){
							$('#dialog .main').html(data);
							$('#dialog .buttons-frame').prepend('<a href="javascript:void(0);" onclick="$.dialog.hide();" class="redbutton"> Close </a>');
							centerDialog();
			    		}); 
			}
			else
			{
				$('#dialog .main').html(data);
				centerDialog();
			}
			
			$(document).bind('scroll.dialog', function(e) { centerDialog(); });

			
			$(document).bind('keydown.dialog', function(e) {
				if (e.keyCode == 27) $.dialog.hide();
				return true;
			})
	        $(document).trigger('show.dialog');
			
			
		},
		hide : function()
		{
			$('#dialog').hide();
			$(document).unbind('scroll.dialog');
			$(document).unbind('keydown.dialog');
	        $(document).trigger('hide.dialog');
			
			
		},
		showAlert : function(data, type, title)
		{
			if (!type) type = 'info';
			if (!$.dialog.isInit)
				$.dialog.initDialog();

			if (title) data = '<div class="alert-header">' + title + '</div>' + data;
			if (type != 'noicon')
				data = '<div class="icon-' + type + '">&nbsp;</div><div style="overflow: hidden;">' + data + '</div>';
			
			$.dialog.show(data);

			$('#dialog .footer').html('');
			if ($('#dialog .buttons-frame').html())
			{
				$('#dialog .buttons-frame').prepend('<a href="javascript:void(0);" onclick="$.dialog.hide();" class="redbutton"> Close </a>');
			}
			else
				$('#dialog .footer').html('<a class="button" href="javascript:void(0)" onclick="$.dialog.hide();" > Close </a>').show();
			
		},
		showDialog : function(data)
		{
			if (!$.dialog.isInit)
				$.dialog.initDialog();
			
			$('#dialog .footer').hide();
			
			$.dialog.show(data);
			
		}		          
  });
  
  	function centerDialog()
  	{
	    $('#dialog').show().css({	left : $(window).width() / 2 - ($('#dialog table').width() / 2), 
			top:	getPageScroll()[1] + (getPageHeight() / 2.5) - ($('#dialog table').height() / 2)});        				
  	}
	
	function getPageScroll() {
	  var xScroll, yScroll;
	  if (self.pageYOffset) {
	    yScroll = self.pageYOffset;
	    xScroll = self.pageXOffset;
	  } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
	    yScroll = document.documentElement.scrollTop;
	    xScroll = document.documentElement.scrollLeft;
	  } else if (document.body) {// all other Explorers
	    yScroll = document.body.scrollTop;
	    xScroll = document.body.scrollLeft;	
	  }
	  return new Array(xScroll,yScroll) 
	}
	
	function getPageHeight() {
	  var windowHeight;
	  if (self.innerHeight) {	// all except Explorer
	    windowHeight = self.innerHeight;
	  } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
	    windowHeight = document.documentElement.clientHeight;
	  } else if (document.body) { // other Explorers
	    windowHeight = document.body.clientHeight;
	  }	
	  return windowHeight
	}	 
})(jQuery);

(function($){
	$.fn.extend({
		  scrollTo : function(speed, easing) {
		    return this.each(function() {
		      var targetOffset = $(this).offset().top;
		      $('html,body').animate({scrollTop: targetOffset}, speed, easing);
		    });
		  }
		});
	
})(jQuery);


$.fn.ajaxSubmit = function(e) {
	/* Change a form's submission type to ajax */
	this.submit(function(){
	
		$(this).find('*').filter("ul.errors").hide();
		$.post(this.getAttribute("action"), $(this).serialize(), function(obj){
			if (obj.status == "success")
			{
    			if (obj.hideDialog)
    				$.dialog.hide();
    			if (obj.submitForm)
    				$('#' + obj.submitForm).submit();
    			if (obj.eval)
    				eval(obj.eval);
    			
    			if (obj.reset == "true")
				{
					$().find('input')
					 .not(':button, :submit, :reset, :hidden')
					 .val('')
					 .removeAttr('checked')
					 .removeAttr('selected');
					$().find('textarea').val('');
				}
				
    			if (obj.message)
    			{
    				if (obj.noicon != "true")
    					$.dialog.showAlert(obj.message, 'info', obj.title);
    				else
    					$.dialog.showAlert(obj.message, 'noicon', obj.title);
    					
    			}
				if (obj.result && obj.target)
					$('#' + obj.target).prepend(obj.result);

				if (obj.redirect)
					window.location = obj.redirect;
			}
			else if (obj.message)
			{ 			
				$.dialog.showAlert(obj.message, 'error', obj.title);

			}
			else
			{
				for (r in obj)
				{
					var err_list = "";
					for (err in obj[r])
					{
						err_list += "<li>" + obj[r][err] + "</li>";
					}
					if ($('#err' + r).length == 0)
					{
						$('#' + r).parent().append('<ul class="errors" id="err' + r + '">' + err_list +  '</ul>');
						$('#err' + r).hide();
					}
					else
						$('#err' + r).html(err_list);	
										
					$('#err' + r).fadeIn();				
				}
				
				if (obj.captcha) {
					$('#' + obj.captcha.field).attr('src', Nid.baseUrl + '/img/captcha/' + obj.captcha.id + '.png');
					$('#' + obj.captcha.field + '-id').attr('value', obj.captcha.id);
					$('#' + obj.captcha.field + '-input').val('');
				}
			}
		}, "json");
		return false;
	});
	
	return this;
}






$(function() { 
	Inv.menu.init();

	$('input[type="text"]').each(function(){
		if ($(this).attr('title') != '') {
			this.value = $(this).attr('title');
			$(this).addClass('text-label');
			$(this).focus(function(){
				if(this.value == $(this).attr('title')) {
					this.value = '';
					$(this).removeClass('text-label');
				}
			});
			$(this).blur(function(){
				if(this.value == '') {
					$(this).addClass('text-label');
					this.value = $(this).attr('title');
				}
			});
		}
	});
	
});



