$(document).ready(function(){

    $('form').live('keypress', function(event){ if(event.keyCode == '13'){ $(this).find('.ajaxsubmit').click();} });

    $('#logout').live('click', function(){
        $.cookie('_mhudata_uuname', null);
        $.cookie('_mhudata_uname', null);
        $.cookie('_mhudata_uemail', null);
    });

    $('.toggle-location, .toggle-location span, .toggle-location-whole').live('click',function() {
      $('.location-select').slideToggle('fast', function() {
      });
      return false;
    });

    $('.newsletter-desc-tip').live('click',function() {
      $('.tip-content').slideToggle('fast', function() {
      });
      return false;
    });
    $('.newsletter-desc-tip-top').live('click',function() {
      $('.tip-content-top').slideToggle('fast', function() {
      });
      return false;
    });

    $('a[rel=showGallery]').live('click', function(){
        console.log($(this).attr('data-item-gid'));
        $('#'+ $(this).attr('data-item-gid')).fadeIn('fast');
        return false;
    });
    $('a.xc_closeGallery').live('click', function(){
        $('.offer-gallery').fadeOut('fast');
        return false;
    });

//	$('a[title]:not(".notip"), input[type="button"]:not(".notip")').live('mouseover', function(event) {
//		// Bind the qTip within the event handler
//		$(this).qtip({
//			overwrite: false, // Make sure the tooltip won't be overridden once created
//		    //content: 'I get bound to all my selector elements, past, present and future!',
//		    show: {
//		    	event: event.type, // Use the same show event as the one that triggered the event handler
//		        ready: true // Show the tooltip as soon as it's bound, vital so it shows up the first time you hover!
//		    },
//		    style: {
//		    	classes: 'ui-tooltip-tipsy ui-tooltip-shadow'
//			},
//			position: {
//				my: 'bottom center',
//			    at: 'top center'
//			}
//		}, event); // Pass through our original event to qTip
//	});

//	$('.desc-tip').live('mouseover', function(event) {
//		// Bind the qTip within the event handler
//		$(this).qtip({
//			overwrite: false, // Make sure the tooltip won't be overridden once created
////			content: $(this).attr('data-item-desc'),
//			content: {
//				text: function(api) {
//			         // Retrieve content from custom attribute of the $('.selector') elements.
//					return $(this).find('.tip-content').html();
//			    },
//			    title: {
//			       text:function(api) {
//				         // Retrieve content from custom attribute of the $('.selector') elements.
//						return $(this).find('.tip-title').html();
//				   },
//			       button: 'Zapri'
//			    }
//			},
//			show: {
//				event: event.type, // Use the same show event as the one that triggered the event handler
//				ready: true // Show the tooltip as soon as it's bound, vital so it shows up the first time you hover!
//			},
//			position: {
//			      target: 'mouse', // Position at the mouse...
//			      adjust: { mouse: false } // ...but don't follow it!
//			 },
//			hide: {
////			    event: 'click',
//				delay: 100,
////				distance: 30 ,// Hide it after we move 15 pixels away from the origin
//				fixed: true
////				effect: function(offset) {
////			         $(this).slideDown(100); // "this" refers to the tooltip
////			    }
//			},
//			style: {
//				classes: 'ui-tooltip-tipsy ui-tooltip-shadow'
//			},
//			position: {
//				my: 'left top',
//				at: 'right middle'
//			}
//		}, event); // Pass through our original event to qTip
//	});
	
	/* Dodajanje itemov */
	$('.xc_remove_oitem').live('click', function(){
		$(this).parent().fadeOut();
	});
	
	/* Odstranim item (lokacija, kategorije) */
	$('.xc_remove_item').live('click', function(){
		$(this).parent().fadeOut('fast', function(){$(this).remove();});
	});

	$('.hide-msg').live('click', function(){
		$(this).parent().html('').slideUp('fast');
        // resetiram še potencijalne cookije, ki so ostali
        $.cookie('_mhalert_type', null, {path:'/', domain: '.microhint.com', expires: 300});
        $.cookie('_mhalert_msg', null, {path:'/', domain: '.microhint.com', expires: 300});
	});
	
	$('#add-oitem').live('click', function(){
		var text = $(this).prev().val();
		var field = $(this).attr('data-item-field');
		
		if(text.length > 5 && text.length < 200)
		{
			$(this).parent().find('ul').append('<li>'+ text +'<input type="hidden" name="'+field+'[]" value="'+text+'"><a class="remove xc_remove_oitem">Odstrani</a></li>');
			$(this).prev().val('');
		}
		else {
			$(this).after('<label class="oitem-error error" style="margin:0 0 0 20px;">Vsaj 5 in ne več kot 200 znakov</label>');
		}
		
		return false;
	});
	$('#oitem-val').live('keyup', function(){
		var text = $(this).val();
		if(text.length < 5 || text.length > 200) {
			$('.oitem-error').remove();
		}
	});
	/* end dodajanje itemov */
	
	$('#open-reject-form').live('click', function(){
		$(this).parent().hide();
		$('#msgpost-form-box').show();
		// XXX omogoči gumb
		
		$('#reject-btn').removeAttr('disabled');
		
		return false;
	});

	$('.why-comment').live('click', function(){
		var microponID = $(this).attr('data-item-id');
		
		
		if ( $(this).hasClass('open') )
		{
			$(this).hide();
			$(this).next().show();

			if ($('#msg-box-'+ microponID).text() == 'nalagam...')
			{
				$.get('ampera/browse-micropon-creation-comments?count=1&cursor=1&microponID='+ microponID, function(data, textStatus, XMLHttpRequest)
						{
					var comment = '';
					
					if(undefined != data)
					{
//				$(data).each(function(i, v){
						var v = data[data.length-1];
						comment += 
							'<div class="post" style="margin:6px 0 0 0px; background:#fff; border-top-left-radius: 6px 6px; border-top-right-radius: 6px 6px; border-bottom-right-radius: 6px 6px; border-bottom-left-radius: 6px 6px;">'
							+'  <div class="comment" style="padding:8px; background: -moz-linear-gradient(top,#FFFCE9 0,#FFF8CC 60px)!important; background: -webkit-gradient(linear,0 0,0 60,from(#FFFCE9),to(#FFF8CC))!important; background: -moz-linear-gradient(top,#FFFCE9 0,#FFF8CC 60px)!important; border: 1px solid #FFE764; -webkit-border-top-left-radius: 0; -moz-border-radius-topleft: 0; border-top-left-radius: 0; -webkit-box-shadow: 2px 2px 8px #CCC; -moz-box-shadow: 2px 2px 8px #CCC; box-shadow: 2px 2px 8px #CCC;">'
							+'   <div class="comment_inner">'
							+'      <div class="meta_data">'
							+'        <span class="author" style="font-size:14px;">'+v.nickname+' pravi: </span>'
							+'        <span class="timestamp" style="font-size:12px; color:#666;">'+v.date_created+'</span>'
							+'      </div>'
							+'		<div class="clearfix"></div>'
							+'      <div class="body"><p>'+decodeURIComponent(v.content)+'</p></div>'
							+'      <div class="chrome"></div>'
							+'    </div>'
							+'  </div>'
							+'</div>';
//				});
					}
					$('#msg-box-'+ microponID).html(comment);
						});
			}
			
		}
		else
		{
			$(this).hide();
			$(this).prev().show();
		}
		
		$('#msg-box-'+ microponID).slideToggle('fast', function(){});
		
		return false;
	});
	
	/**
	 * User selects which store to manage
	 */
	$('.mng-store').live('click', function(e){
		
		var $clicked_el = $(this);				// <a> link for following
		
        // Najprej prikažem dialog (spinner indicator)
        this._dialog = $('<div id="manage-store"><div class="big-spinner">počakaj trenutek...</div></div>')
                    .dialog({
                        autoOpen: true,
                        dialogClass: 'in-dialog-org-list',
                        zIndex:   99999,
                        modal:    true,
                        title:    'Izberi organizacijo, ki jo želiš upravljati',
                        width:    500,
                        minHeight: 56,
                        position: ['center',108],
                        close: function(event, ui) { $(this).remove(); }
        });

	    // Sestavim sezname za izbiro
		$.get('/browse_my_stores?user_nick='+ document.username, function(data){
		    var _content = '';
            if(data.stores != undefined) {
		        $.each(data.stores, function(i, v){
				    var store = v.store;
					_content += '<li class="ui-dialog-org-list-li gradient rounded content"><a href="/#!/manage-store/'+ store.store_slug +'" class="select-store"><div class="company_name">'+ store.company_name +'</div></a></li>';
//					_content += '<li class="ui-dialog-org-list-li gradient rounded content"><a href="/#!/manage-store/'+ store.store_slug +'" class="select-store"><div class="company_name">'+ store.company_name +'</div><div class="company_address">Pod Taborom 9, 6210 Sežana</div></a></li>';
				});
			}
			else {
                _content = '<div class="empty-wall-msg" style="width: 400px; margin: 10px auto 10px auto;"><span class="empty-wall-msg-inner" style="font-size: 14px;">Opala, trenutno ne upravljaš nobene organizacije. Če kakšno poznaš, nas priporoči in tako pomagaj izboljšati okraj v katerem živiš. Super, ne? </span><div class="logo-font" style="text-align: right;">microhint</div></div>';
			}

			$('#manage-store').find('.big-spinner').replaceWith('<ul class="ui-dialog-org-list">'+ _content +'</ul>');

            // še akcije, ki na izbiro zapre dialog
            $('.ui-dialog-org-list-li').bind('click', function(){ $('.in-dialog-org-list').remove(); $('#manage-store').remove(); });
		});

		return false;
	});
	
    /**
     * Submit trgovino na naslednji korak
     */
    $('.status-submit').live('click', function(){
    	var $clickEl = $(this);
    	var $tr = $(this).parents('tr');
    	var status = $(this).attr('data-item-status');
    	var storeID = $(this).attr('data-item-id');
    	
//    	console.log($tr);
    	
    	// If the button is enabled
    	if ($clickEl.is(':disabled') == false)
    	{
    		$.ajax({
    			type: 'POST',
    			url: '/ampera/update-store-status',
    			data: 'storeID='+ storeID +'&status='+ status,
    			success: function(data)
    			{
    				if(data.notice != undefined && data.notice.msgType == 'success')
    				{
    					MHT.utils.flashMessanger(data.notice.msgType, data.notice.msg);
    					$tr.fadeOut('slow');
    				}
    			}
    		});
    	}
    });
    
    $('.ampera_unactive-select a, .ampera_activatedSend-select a').live('click', function(){
    	
    	var $clickEl = $(this);
    	var status = $clickEl.attr('data-item-action');
    	var $submitBTN = $clickEl.parent('li').parent().parent().parent().find('.status-submit');
    	// change status of submission
    	$submitBTN.attr('data-item-status', status);
    	
    	if ($submitBTN.is(':disabled') == true)
    	{
    		$submitBTN.removeAttr("disabled");
    	}
    });
	
	
	// Custom checkbox handling
	$('ul.custom-checkbox li a').live('click', function(e){
		var $clicked_el = $(this);
		if($clicked_el.hasClass('checked')) { $clicked_el.removeClass('checked'); }
		else { $clicked_el.addClass('checked'); }
		return false;
	});
	
	// Custom checkbox handling
//	$('ul.mht-checkbox li a').not('.nochk').live('click', function(e){
	$('ul.mht-checkbox li a').live('click', function(e){
		var $clicked_el = $(this);
		var parent = $clicked_el.parent('li');
		var root = $("#wizard");
		
		if($clicked_el.hasClass('checked')) 
		{ 
			$clicked_el.removeClass('checked');
			if(parent.hasClass('hideField'))
			{
				parent.removeClass('hideField');
				parent.addClass('showField');
				root.css('height', (root.find('.page').eq(1).height() + 30)+'px');
			}
		}
		else 
		{ 
			$clicked_el.addClass('checked'); 
			if(parent.hasClass('showField'))
			{
				parent.removeClass('showField');
				parent.addClass('hideField');
				root.css('height', (root.find('.page').eq(1).height() + 30)+'px');
			}
		}
		return false;
	});
	// Custom radios handling
	$('ul.mht-radios li a').live('click', function(e){
		var $clicked_el = $(this);
		var $ul = $clicked_el.parents('ul');
		$ul.find('li a').removeClass('checked');
		$clicked_el.addClass('checked');
		
		$ul.find('input[name="gender"]').val($clicked_el.attr('data-item-id'));
		return false;
	});
	
	/* --------------------- */
	/* FORMS DIALOGS		 */
	/* --------------------- */
	
    // Submitting trigger for every <a> with class 'submit'
//    $('.submit').live('click', function(){
//    	$(this).parents('form').submit();
//    });
    
	/*
	 * CONTROLS
	 * */
	$('.comments-show').live('click', function(e){
		$parent = $(this).parent();
		$comments = $parent.next();
		
		if($comments.is(':hidden')){
			$comments.slideDown();
//			$(this).text('Skrij');
			$parent.addClass('open');
		} else {
			$comments.slideUp();
//			$(this).text('Prikaži');
			$parent.removeClass('open');
		}
		return false;
	});

	/*
	 * OVERLAY DIALOG comment/reply
	 * */
	document.overlayOptions = {
			// some mask tweaks suitable for modal dialogs
			mask: {
				color: '#333',
				loadSpeed: 200,
				opacity: 0.4
			},
			closeOnClick: false,
			onBeforeLoad: function(e){
				var statusID = $(e.srcElement).parents('.status').attr('id');
				$('ul.reply-to-status').html($('#'+statusID).clone());
			},
			onLoad: function(e){
				$('#comment').focus();
			}	
	};
	

	$('#login-link').live('click', function(){
		// skrijem login in prikažem reset form
		$('#pwd-reset-request-form').fadeOut('fast', function(){
            $('#ui-dialog-title-99').text('Prijavi se, obstoječi uporabnik');
			$('#login-form').fadeIn('fast');
		});
	});

	$('#send-conformation-email-link').live('click', function(){

		$hook = $(this).parent();
		email = $('#login-form').find('input[name="email"]').val();

		$hook.html($('<span style="display:none;">Pošiljam...</span>').fadeIn('fast'));

		$.post(
				$(this).attr('href'),
				{ 'email': email },
				function(data){
					$('#signup_form, #hor-line').hide();
					$hook.parent().replaceWith($('<span style="display:none; background:url(/public/images/check_mark.png) no-repeat 10px 8px;">Email je uspešno poslan... V njemu imaš URL, ki ga klikneš za potrditev emaila, nato se lahko prijaviš.</div>').fadeIn('fast'));
				}
		);
		return false;
	});
	$('#send-conformation-email-inbound-link').live('click', function(){

		$hook = $(this).parent();
		email = $(this).attr('data-item-email');

//		//console.log($hook);
		$hook.html($('<span style="display:none;">Pošiljam...</span>').fadeIn('fast'));

		$.post(
				$(this).attr('href'),
				{ 'email': email },
				function(data){
					$hook.parent().replaceWith($('<div style="display:none; padding:20px 16px 16px 40px; font-size:1.4em; background:url(/public/images/check_mark.png) no-repeat 10px 8px;">Email je uspešno poslan... V njemu imaš URL, ki ga klikneš za potrditev emaila.</div>').fadeIn('fast'));
				}
		);
		return false;
	});

//	/**
//	 * Login form
//	 */
//	$('a[rel=#login]').live('click', function(){
//
//		var $clickEl     = $(this);
//		var gotoURL      = $clickEl.attr('data-item-goto');
//		var forceGotoURL = $clickEl.attr('data-item-force-goto');
//
//        if(forceGotoURL != undefined ) { $('input[name="redirect"]').val(forceGotoURL); }
//
//		$clickEl.overlay({
//			mask: {
//				color: '#333',
//				loadSpeed: 20,
//				opacity: 0.4
//			},
//			closeOnClick: false,
//			onBeforeLoad: function(e){
//
//                /** OBRAZEC ZA RESET GESLA */
//                var _$formPWDReset = $('form#pwd-reset-request-form');
//                _$formPWDReset.validate({
//			        rules: {
//			            email: {
//			                required: true,
//			                email: true
//			            }
//			        },
//			        messages: {
//			            email: {
//			                required: "Vnesi veljaven email naslov" ,
//			                email: "Vnesi veljaven email naslov"
//			            }
//			        }
//			    });
//
//                _$formPWDReset.find('#send-reset-pwd-email-inbound-link').bind('click', function(){
//
//                    if( !_$formPWDReset.valid() ) return false;
//
//                    var query = {
//                        'email':    _$formPWDReset.find('input[name=email]').val()
//                    };
//
//                    $.post(
//                            document.mh_pages_host+'/account/pwd-reset-request',
//                            query,
//                            function(data){
//                                $clickEl.data('overlay').close();
//                                MHT.utils.flashMessanger(data.notice.msgType, data.notice.msg);
//                            }
//                    );
//                    return false;
//                });
//
//
//                /** OBRAZEC ZA PRIJAVO V SISTEM */
//                var _$form = $('form#login-form');
//			    _$form.validate({
//			        rules: {
//			            password: {
//			                required: true,
//			                minlength: 5
//			            },
//			            email: {
//			                required: true,
//			                email: true
//			            }
//			        },
//			        messages: {
//			            password: {
//			                required: "Vpiši geslo",
//			                minlength: jQuery.format("Vnesi vsaj {0} znakov")
//			            },
//			            email: {
//			                required: "Vnesi veljaven email naslov" ,
//			                email: "Vnesi veljaven email naslov"
//			            }
//			        }
//			    });
//
//                _$form.find('.ajaxsubmit').bind('click', function()
//				{
//					if( !_$form.valid() ) return false;
//
//					var $click_el = $(this);
//
//                    var _txt_button = $click_el.text();
//                    $click_el.text('trenutek...');
//
//                    // NOTE: Tule je predpostavka, da imam SAMO 1 datum, ne več njih!!
//                    var query = {
//                        'email':    _$form.find('input[name=email]').val(),
//                        'password': _$form.find('input[name=password]').val()
//                    };
//
//                    _$form.prop('action','/authenticate');
//
//					var jqxhr = $.ajax({
//							type: 	'POST',
//                            //xhrFields: { withCredentials: true },
//                            dataType: 'json',
//                            //crossDomain: true,
//							url: 	document.mh_pages_host+'/authenticate',
//							data:  	query
//					});
//
//					jqxhr.success(function(data, textStatus, jqXHR)
//					{
//                        if(data.users != undefined)
//			        	{
//			        		var user = data.users[0].user;
//
//			       			// If extra url is not given, then jump to home page!
//			        		if(forceGotoURL != undefined ){ gotoURL = forceGotoURL; }
//                            else if(gotoURL == undefined) { gotoURL = '/#!/my-stuff/'+ user.nickname; }
//
//			        	    window.location = '/redirect-to?url='+ gotoURL;
////			        		$clickEl.data('overlay').close();
////			        		_$form.parent().unblock();
//			        	}
////			        	else {
////			        		_$form.parent().unblock();
////			        	}
//
////                        if(data.success == true){
////                            // če sem ugotovil, da je prijava prava
////                            _$form.append('<input type="hidden" name="check" id="check" value="ok">');
////                            _$form.submit();
////                        }
////                        else {
//                            _$form.find('#login-error-notice').html(data);
////                        }
//
//					}).error(function(jqXHR, textStatus, errorThrown)
//                    {
//                       //_$form.find('#login-error-notice').html('Server je zaribal :| Poskusi kasneje ponovno, hvala.');
//					}).complete(function(jqXHR, textStatus) {
//                        $click_el.text(_txt_button);
//                    });
//					return false;
//				});
//
//			},
//			onLoad: function(e){
//				//$('#login-form #email').focus();
//			},
//			load: true
//		});
//        return false;
//	});

//	/**
//	 * Register form
//	 */
//	$('a[rel=#register]').live('click', function(){
//
//		var $clickEl     = $(this);
//		var gotoURL      = $clickEl.attr('data-item-goto');
//		var forceGotoURL = $clickEl.attr('data-item-force-goto');
//
//        if(forceGotoURL != undefined ) { $('input[name="redirect"]').val(forceGotoURL); }
//
//		$clickEl.overlay({
//			// some mask tweaks suitable for modal dialogs
//			mask: {
//				color: '#333',
//				loadSpeed: 20,
//				opacity: 0.4
//			},
//			closeOnClick: false,
//			onBeforeLoad: function(e){
//                // Vstavim validator za registracijo sem
//                // validate signup form on keyup and submit
//                $("#signup_form").validate({
//                    rules: {
//                        name: {
//                            required: true,
//                            minlength: 5,
//                            maxlength: 40
//                        },
//                        email: {
//                            required: true,
//                            email: true,
//                            remote: '/field-precheck'
//                        },
//                        nickname: {
//                            required: true,
//                            minlength: 1,
//                            remote: '/field-precheck'
//                        },
//                        password: {
//                            required: true,
//                            minlength: 6,
//                            maxlength: 12
//                        }
//                    },
//                    messages: {
//                        name: {
//                            required: "Vpiši svoj Ime in Priimek",
//                            minlength: jQuery.format("Vnesi vsaj {0} znakov"),
//                            maxlength: jQuery.format("Vnesi največ {0} znakov")
//                        },
//                        email: {
//                            required: "Vnesi veljaven email naslov" ,
//                            email: "Vnesi veljaven email naslov",
//                            remote: 'Ta email je že pri nas že registriran.'
//                        },
//                        nickname: {
//                            required: "Vnesi kratek nickname" ,
//                            minlength: jQuery.format("Vnesi vsaj {0} znakov"),
//                            remote: "Ta nickname je žal zaseden"
//                        },
//                        password: {
//                            required: "Ne pozabi na geslo",
//                            minlength: jQuery.format("Vnesi vsaj {0} znakov"),
//                            maxlength: jQuery.format("Vnesi največ {0} znakov")
//                        }
//                    },
//                    submitHandler: function(form) {
//                        $(form).parent().block({ message: null });
//
//                        $(form).find(':submit').val('Shranjujem...');
//
//                        $(form).ajaxSubmit({
//                            type: 'POST',
//                            target: "#login-error-notice",
//                            success: function(data, textStatus, XMLHttpRequest)
//                            {
//                                if(data.notice.msgType == 'success') {
//                                    MHT.utils.flashMessanger(data.notice.msgType,'Email je uspešno poslan. V njemu imaš URL, ki ga klikneš za zaključek registracije.');
//                                    $clickEl.data('overlay').close();
//			        				$(form).parent().unblock();
//                                    $(form).find('input').not(':submit').val('');
//                                }
//                                else {
//                                    $(form).find(':submit').val('Ustvari nov račun');
//                                    MHT.utils.flashMessanger('error','Prišlo je do neke napake. Probaj se prijavit/registrirati kasneje. O napaki smo bili obvešeleni.');
//                                    $clickEl.data('overlay').close();
//			        				$(form).parent().unblock();
//                                }
//                            }
//                        });
//                        return false;
//                    }
//                });
//			},
//			onLoad: function(e){
//				//$('#login-form #email').focus();
//			},
//			load: true
//		});
//        return false;
//	});
	
	$('.list_item_toggle').live('click', function(){
		$(this).parent().parent().find('.toggle_content').toggle('fast');
		return false;
	});
	
	/**
	 * Sprožim čiščenje rezervacij v amperi
	 */
	$('#resolveReservations').live('click', function(){
		$.get('/ampera/resolve-reservations', function(data){
			if(data.length > 0) {
				$(data).each(function(i, transaction){
					if(undefined != transaction.reference) {
						$.get('/callback/megapos-update?txId='+ transaction.reference);
					}
				});
			}
		});
	});

	/**
	 * Sprožim dnevni email v amperi
	 */
	$('#dailyDealNewsletter').live('click', function(){
		$.get('/ampera/send-daily-deal-newsletter', function(data){
			MHT.utils.flashMessanger('success', 'Super ok, dnevni email poslan, dalje!');
		});
	});

	$('#donatorNewsletter').live('click', function(){
		$.get('/ampera/send-donator-newsletter', function(data){
			MHT.utils.flashMessanger('success', 'Super ok, donatorski email poslan, dalje!');
		});
	});

	/* Sharer */
	$('.share-on-fb').live('click', function(){
		
		var fb_url 		= $(this).attr('href');
		var fb_title 	= $(this).attr('data-item-title');
		var fb_status 	= $(this).attr('data-item-status');
		var fb_image	= decodeURIComponent( 'http://'+ document.location.host + $(this).attr('data-item-pic') );
        var fb_caption  = $(this).attr('data-item-caption');

//        FB.getLoginStatus(function(response) {
//         if (response.session) {
//           console.log('got session, ok to post');
//         } else {
//            FB.login(function(response) {
//              if (response.session) {
//                console.log('user logged in');
//              } else {
//                console.log('canceled login');
//              }
//            });
//         }
//       });

		FB.ui(
				{
					method:  'feed',
					display: 'popup',
					//display: 'iframe',
                    name:    fb_title,
                    link:    fb_url,
                    picture: fb_image,
                    description: fb_status,
                    caption	   : fb_caption
				},
				function(response) {
					if (response && response.post_id) {
						//alert('Post was published.');
					} else {
						//alert('Post was not published.');
					}
				}
		);
		return false;
	});

    $('.test-bf').live('click', function(){
//        FB.api({
//            method: 'fql.query',
//            query: 'SELECT name FROM user WHERE uid=me()'
//        },
//        function(response) {
//            alert('Your name is ' + response);
//        });
    });

	
//	 $('.share-on-tw').live('click',function() {
//
//		    var width  = 540,
//		        height = 450,
//		        left   = ($(window).width()  - width)  / 2,
//		        top    = ($(window).height() - height) / 2;
//
//            var width  = 550,
//		        height = 450;
//
//            console.log(left);
//            console.log(top);
//
//            var tw_user = encodeURIComponent('Microhint_com');
//
//		    twwindow = window.open('http://twitter.com/share?url=https%3A%2F%2Fwww.microhint.com&amp;via='+tw_user, 'twitter', 'status=1,width=550px,height=450px');
//            twwindow.moveTo(left,top);
//
//
//		    return false;
//		  });

    /* PRIJAVA, REGISTRACIJA, PWD RESET */

	// **** PWD
	$('#pwd-reset-request-link').live('click', function(){
		// skrijem login in prikažem reset form
		$('#login-form').fadeOut('fast', function(){
            $('#ui-dialog-title-99').text('Na email dobiš url za zamenjavo gesla');
			$('#pwd-reset-request-form').fadeIn('fast');
		});
        return false;
	});

	// **** END PWD

	$('#login-link').live('click', function(){
		// skrijem login in prikažem reset form
		$('#pwd-reset-request-form').fadeOut('fast', function(){
            $('#ui-dialog-title-99').text('Prijavi se, obstoječi uporabnik');
			$('#login-form').fadeIn('fast');
		});
        return false;
	});

	$('#send-conformation-email-link').live('click', function(){

		$hook = $(this).parent();
		email = $('#login-form').find('input[name="email"]').val();

		$hook.html($('<span style="display:none;">Pošiljam...</span>').fadeIn('fast'));

		$.post(
				$(this).attr('href'),
				{ 'email': email },
				function(data){
					$('#signup_form, #hor-line').hide();
					$hook.parent().replaceWith($('<span style="display:none; background:url(/public/images/check_mark.png) no-repeat 10px 8px;">Email je uspešno poslan... V njemu imaš URL, ki ga klikneš za potrditev emaila, nato se lahko prijaviš.</div>').fadeIn('fast'));
				}
		);
		return false;
	});
	$('#send-conformation-email-inbound-link').live('click', function(){

		$hook = $(this).parent();
		email = $(this).attr('data-item-email');

//		//console.log($hook);
		$hook.html($('<span style="display:none;">Pošiljam...</span>').fadeIn('fast'));

		$.post(
				$(this).attr('href'),
				{ 'email': email },
				function(data){
					$hook.parent().replaceWith($('<div style="display:none; padding:20px 16px 16px 40px; font-size:1.4em; background:url(/public/images/check_mark.png) no-repeat 10px 8px;">Email je uspešno poslan... V njemu imaš URL, ki ga klikneš za potrditev emaila.</div>').fadeIn('fast'));
				}
		);
		return false;
	});

	/**
	 * Login form
	 */
	$('a[rel=#login]').live('click', function(){

		var $clickEl     = $(this);
		var gotoURL      = $clickEl.attr('data-item-goto');
		var forceGotoURL = $clickEl.attr('data-item-force-goto');

        if(forceGotoURL != undefined ) { $('input[name="redirect"]').val(forceGotoURL); }

		$clickEl.overlay({
			mask: {
				color: '#333',
				loadSpeed: 20,
				opacity: 0.4
			},
			closeOnClick: false,
			onBeforeLoad: function(e){

                /** OBRAZEC ZA RESET GESLA */
                var _$formPWDReset = $('form#pwd-reset-request-form');
                _$formPWDReset.validate({
			        rules: {
			            email: {
			                required: true,
			                email: true
			            }
			        },
			        messages: {
			            email: {
			                required: "Vnesi veljaven email naslov" ,
			                email: "Vnesi veljaven email naslov"
			            }
			        }
			    });

                _$formPWDReset.find('#send-reset-pwd-email-inbound-link').bind('click', function(){

                    if( !_$formPWDReset.valid() ) return false;

                    var query = {
                        'email':    _$formPWDReset.find('input[name=email]').val()
                    };

                    $.post(
                            '/account/pwd-reset-request',
                            query,
                            function(data){
                                $clickEl.data('overlay').close();
                                MHT.utils.flashMessanger(data.notice.msgType, data.notice.msg);
                            }
                    );
                    return false;
                });


                /** OBRAZEC ZA PRIJAVO V SISTEM */
                var _$form = $('form#login-form');
			    _$form.validate({
			        rules: {
			            password: {
			                required: true,
			                minlength: 5
			            },
			            email: {
			                required: true,
			                email: true
			            }
			        },
			        messages: {
			            password: {
			                required: "Vpiši geslo",
			                minlength: jQuery.format("Vnesi vsaj {0} znakov")
			            },
			            email: {
			                required: "Vnesi veljaven email naslov" ,
			                email: "Vnesi veljaven email naslov"
			            }
			        }
			    });

                _$form.find('.ajaxsubmit').bind('click', function()
				{
					if( !_$form.valid() ) return false;

					var $click_el = $(this);

                    var _txt_button = $click_el.text();                                 // najdem trenutni submit click
                    var _$coll_elements = _$form.find(':input').not('.mh_disabled');    // najdem vse elmente, ki niso explicitno preklicani
                    _$coll_elements.prop('disabled', true);
                    $click_el.text('trenutek...');

                    var query = {
                        'email':    _$form.find('input[name=email]').val(),
                        'password': _$form.find('input[name=password]').val()
                    };

                    _$form.prop('action',document.mh_pages_host+'/authenticate');

					var jqxhr = $.ajax({
							type: 	'POST',
                            dataType: 'json',
							url: 	'/authenticate',
							data:  	query
					});

					jqxhr.success(function(data, textStatus, jqXHR)
					{
                        if(data.users != undefined)
			        	{
			        		var user = data.users[0].user;

			       			// If extra url is not given, then jump to home page!
			        		if(forceGotoURL != undefined ){ gotoURL = forceGotoURL; }
                            else if(gotoURL == undefined) { gotoURL = '/#!/my-stuff/'+ user.nickname; }

			        	    window.location = '/redirect-to?url='+ gotoURL;
			        	}
                        _$form.find('#login-error-notice').html(data);

					}).error(function(jqXHR, textStatus, errorThrown)
                    {
                        _$form.find('#login-error-notice').html('Server je zaribal :| Poskusi kasneje ponovno, hvala.');
					}).complete(function(jqXHR, textStatus) {
                        _$coll_elements.prop('disabled', false);
                        $click_el.text(_txt_button);
                    });
					return false;
				});

			},
			onLoad: function(e){},
			load: true
		});
        return false;
	});

	/**
	 * Register form
	 */
	$('a[rel=#register]').live('click', function(){

		var $clickEl     = $(this);
		var gotoURL      = $clickEl.attr('data-item-goto');
		var forceGotoURL = $clickEl.attr('data-item-force-goto');

        if(forceGotoURL != undefined ) { $('input[name="redirect"]').val(forceGotoURL); }

		$clickEl.overlay({
			// some mask tweaks suitable for modal dialogs
			mask: {
				color: '#333',
				loadSpeed: 20,
				opacity: 0.4
			},
			closeOnClick: false,
			onBeforeLoad: function(e){

                var _$form = $('form#signup_form');
                _$form.validate({
                    rules: {
                        name: {
                            required: true,
                            minlength: 5,
                            maxlength: 40
                        },
                        email: {
                            required: true,
                            email: true,
                            remote: '/field-precheck'
                        },
                        nickname: {
                            required: true,
                            minlength: 1,
                            remote: '/field-precheck'
                        },
                        password: {
                            required: true,
                            minlength: 6,
                            maxlength: 12
                        }
                    },
                    messages: {
                        name: {
                            required: "Vpiši svoj Ime in Priimek",
                            minlength: jQuery.format("Vnesi vsaj {0} znakov"),
                            maxlength: jQuery.format("Vnesi največ {0} znakov")
                        },
                        email: {
                            required: "Vnesi veljaven email naslov" ,
                            email: "Vnesi veljaven email naslov",
                            remote: 'Ta email je že pri nas že registriran.'
                        },
                        password: {
                            required: "Ne pozabi na geslo",
                            minlength: jQuery.format("Vnesi vsaj {0} znakov"),
                            maxlength: jQuery.format("Vnesi največ {0} znakov")
                        }
                    }
                });

                _$form.find('.ajaxsubmit').bind('click', function()
				{
					if( !_$form.valid() ) return false;

					var $click_el = $(this);

                    // NOTE: Tule je predpostavka, da imam SAMO 1 datum, ne več njih!!
                    var query = {
                        'name':     _$form.find('input[name=name]').val(),
                        'email':    _$form.find('input[name=email]').val(),
                        'password': _$form.find('input[name=password]').val()
                    };

                    if($.cookie("_mhref") != undefined) { query['_mhref'] = $.cookie("_mhref"); };

					var jqxhr = $.ajax({
							type: 	'POST',
                            dataType: 'json',
							url: 	'/account/signup',
							data:  	query
					});

					jqxhr.success(function(data, textStatus, jqXHR)
					{
                        if(data.users != undefined)
			        	{
			        		var user = data.users[0].user;
                            $('#register, #exposeMask').hide();

                            var _emailHost = user.email.split('@');

                            MHT.utils.flashMessanger('success', 'Super!! Uspešno si ustvaril nov račun. Rabimo še potrditev tvojega email naslova <strong>'+user.email+'</strong>, da se prepričamo da je v tvoji lasti. Prijaviš se v svoj email <strong><a href="http://'+_emailHost[1]+'" target="_self" style="text-decoration: underline; color: #5EB8DF;">'+_emailHost[1]+'</a></strong> in klikneš link - simpl :)');
                            return false;
			        	}
                        _$form.find('#register-error-notice').html(data);

					}).error(function(jqXHR, textStatus, errorThrown)
                    {
                       _$form.find('#register-error-notice').html('Server je zaribal :| Poskusi kasneje ponovno, hvala.');
					}).complete(function(jqXHR, textStatus) {});
					return false;
				});
			},
			onLoad: function(e){
				//$('#login-form #email').focus();
			},
			load: true
		});
        return false;
	});

});
