
var currentPage = 'unknown';

function updateSelect(index, target) {
	var value = $(target).attr('rel');
	var options = $(target).children('option');  
	
	for(var i=0; i < options.length; i++) {
		if($(options[i]).attr('value') == value) {
			$(options[i]).attr('selected', 'selected');
			break;
		}
	}
}

function psmfRemoveShadow() {
    $('.dropShadow').remove();
}

function psmfShowShadow() {
    if ( typeof $('.message-header').dropShadow == 'function' ) {
        $('.message-header').dropShadow({
            'left': 0,
            'top': 0,
            'blur': 2,
            'opacity': 0.5,
            'color': "black",
            'swap': false
        });
    }
}

function psmfResetShadow() {
    psmfRemoveShadow();
    psmfShowShadow();
}

function showMessageSentNotification(credits,messageSentAction) {
    if ( undefined !== credits && credits != '' && credits != 0 ) {
        var creditString = credits+' credits';
        if ( credits > 0 ) {
            creditString = '+'+creditString;
        }
        $('#profile_message_sent span.credits').html(creditString);
    } else {
        $('#profile_message_sent span.credits').html('');
    }
    psmfRemoveShadow();
    var srcColor = $('#login-bar-background').css('background-color');

    $('#profile_message_sent').css('background-color',$('#login-bar-background').css('background-color'));
    $('#profile_message_sent').slideDown(function(event){
        $('#profile_message_sent').effect("highlight", { color: '#D3D3D3' }, 1000);
        setTimeout("$('#profile_message_sent').effect('highlight', { color: '#D3D3D3' }, 1000);",1000);
        setTimeout("$('#profile_message_sent').effect('highlight', { color: '#D3D3D3' }, 1000);",2000);
        setTimeout("$('#profile_message_sent').effect('highlight', { color: '#D3D3D3' }, 1000);",3000);
        psmfResetShadow();
        setTimeout("psmfRemoveShadow();$('#profile_message_sent').slideUp(function(){ psmfResetShadow(); });",3700);
        if ( messageSentAction !== undefined && messageSentAction != null && messageSentAction != '' ) {
            setTimeout(messageSentAction,4300);
        }
    });
}

function psmfShowError(message) {
    $('#psmf_error').html(message);
    $('#psmf_error').show();
    if ( !psmfErrorVisible ) {
        psmfResetShadow();
        psmfErrorVisible = true;
    }
}

function psmfHideError() {
    $('#psmf_error').hide();
    if ( psmfErrorVisible ) {
        psmfResetShadow();
        psmfErrorVisible = false;
    }
}

function psmfShowSubjectError(message) {
    $('#psmf_subject_error').html(message);
    $('#psmf_subject_error').show();
    if ( !psmfSubjectErrorVisible ) {
        psmfResetShadow();
        psmfSubjectErrorVisible = true;
    }
}

function psmfHideSubjectError() {
    $('#psmf_subject_error').hide();
    if ( psmfSubjectErrorVisible ) {
        psmfResetShadow();
        psmfSubjectErrorVisible = false;
    }
}

function psmfOpenSendMessage() {
    if ( !psmfSendMessageOpen ) {
        psmfRemoveShadow();
        $('#profile_send_message').slideDown(500,function(){
            $('#psmf_subject').focus();
            psmfResetShadow();
        });
        psmfSendMessageOpen = true;
    } else {
        $('#profile_send_message div.title-overlay').effect("highlight", {color: '#555'}, 50);
        $('#profile_send_message div.title-overlay').effect("highlight", {color: '#555'}, 50);
        $('#psmf_subject').focus();
    }
}

function psmfCloseSendMessage() {
    if ( psmfBuyCreditsVisible ) {
        psmfHideBuyCredits();
        setTimeout('psmfCloseSendMessage()',500);
    } else {
        psmfRemoveShadow();
        $('#profile_send_message').slideUp(function(){
            psmfSendMessageOpen = false;
            $('#psmf_continue_message').val('');
            $('#psmf_subject').removeAttr('readonly');
            $('#psmf_message').removeAttr('readonly');
            $('#psmf_attachment').removeAttr('disabled');
            $('#psmf_subject').val('');
            $('#psmf_message').val('');
            $('.buy_credits_phone_field').val('');
            $('#psmf_submit').show();
            psmfResetShadow();
        });
    }
}

function psmfShowCreditsError(message) {
    $('#psmf_credits_error').html(message);
    $('#psmf_credits_error').show();
    if ( !psmfCreditsErrorVisible ) {
        psmfCreditsErrorVisible = true;
    }
}

function psmfHideCreditsError() {
    $('#psmf_credits_error').hide();
    if ( psmfCreditsErrorVisible ) {
        psmfCreditsErrorVisible = false;
    }
}

function psmfShowMessageError(message) {
    $('#psmf_message_error').html(message);
    $('#psmf_message_error').show();
    if ( !psmfMessageErrorVisible ) {
        psmfResetShadow();
        psmfMessageErrorVisible = true;
    }
}

function psmfHideMessageError() {
    $('#psmf_message_error').hide();
    if ( psmfMessageErrorVisible ) {
        psmfResetShadow();
        psmfMessageErrorVisible = false;
    }
}

function psmfShowBuyCredits(paymentData) {
    psmfPhonePaymentData = paymentData;
    if ( !psmfBuyCreditsVisible ) {
        $('#psmf_submit').hide();
        psmfChangeBuyCreditsLanguage(psmfPhonePaymentData.def);
        psmfRemoveShadow();
        $('#psmf_buy_credits').animate(
                {height:($('#psmf_buy_credits').height()+195)+'px'},
                500,null, function() {
                    psmfResetShadow();
                });
        $('#psmf_buy_credits').fadeIn(500);
        psmfBuyCreditsVisible = true;
    }
}

function psmfHideBuyCredits() {
    if ( psmfBuyCreditsVisible ) {
        psmfRemoveShadow();
        $('#psmf_buy_credits').fadeOut(500);
        $('#psmf_buy_credits').animate(
                {height:($('#psmf_buy_credits').height()-195)+'px'},
                500,null, function() {
                    psmfResetShadow();
                });
		  $('#psmf_attachment').attr('disabled', '');
        psmfBuyCreditsVisible = false;
    }
}

function psmfChangeBuyCreditsLanguage(language) {
    $('.buy_credits_language_select').show();
    $('#psmf_credits_select_'+language).hide();
    var paymentData = eval("psmfPhonePaymentData."+language+";");
    $('#psmf_credits_number_price').html(paymentData.tariff);
    $('#psmf_credits_phone_number .phone_number').html(paymentData.number);
    $('.phone_number_images').hide();
    $('#phone_number_'+language).show();
    $('#psmf_credits_phone_language').val(paymentData.country_code);
}

var globalData;
var globalErrors;

/**
 * Photo upload calls callback with data containing:
 * file_type, file_size, file_size_formatted
 * Or display an error.
 */
function psmfPhotoUpload(callback)
{
    $.ajaxFileUpload({
        url:'/ajax/photo-upload.php',
        secureuri:false,
        fileElementId:'psmf_attachment',
        dataType: 'json',
        success: function (data) {
				$('#psmf_attachment').val('');
				$('#psmf_attachment').attr('disabled', 'disabled');

            data = eval(data);
            if ( data.ok ) {
                var result = data.data;
                callback(result);
            } else {
                $.each(data.errors, function(idx, err){
                    psmfShowError(err.desc);
                });
            }
        }
    });
    return false;
}

function psmfFormSubmit(result) {
    psmfHideSubjectError();
    psmfHideMessageError();
    psmfHideError();
    
    if ($('#psmf_attachment').val() != '' && (typeof $('#psmf_attachment').attr('disabled') != 'undefined')) //first upload photo
	 {
			psmfPhotoUpload(psmfFormSubmit);
    } else {
        if ( $('#psmf_subject').val() == $('#psmf_subject').attr('title') ) {
            $('#psmf_subject').val('');
        }
        if ( $('#psmf_message').val() == $('#psmf_message').attr('title') ) {
            $('#psmf_message').val('')
        }

		  if (result && result.file_name)
		  {
				$("#user_message_image").val(result.file_name);
		  }

        $.post('/ajax/psmf-post.php', $('#profile_send_message_form').serialize(),function(data){
				data = eval(data);
				if ( data.ok ) {

					 var result = data.data;
					 psmfCloseSendMessage();
					 showMessageSentNotification(0-result.cost, messageSentAction);

					$("#user_message_image").val('');
				} else {
					 //alert(data.errors[0].desc);
					 $.each(data.errors,function(idx, err){
						  if ( err.code == 'buy_credits' ) {
								$('#psmf_continue_message').val('yes');
								$('#psmf_subject').attr('readonly','true');
								$('#psmf_message').attr('readonly','true');
								$('#psmf_attachment').attr('disabled','disabled');
								psmfShowBuyCredits(data.data);
						  }
						  if ( err.code == 'subject_too_long' ) {
								psmfShowSubjectError(err.desc);
						  }
						  if ( err.code == 'text_too_lang' ) {
								psmfShowMessageError(err.desc);
						  }
						  if ( err.code == 'purchase_code_not_valid' ) {
								psmfShowCreditsError(err.desc);
						  }
						  $.scrollTo('#setfocus'); 
					 });
				}
        },'json');
    }
}


String.prototype.trim = function () {
	return this.replace(/^[\s]+(.+?)[\s]+$/, '$1');
}


$(document).ready(function(){
    $('#change_password_btn').click(function(e) {
            e.preventDefault();
            $('#menu_help').hide();
            $.hp.dialogs.changePassword();
            return false;
    });    
    
    $('#contact_btn').click(function(e) {
                e.preventDefault();
                var form = $(this).closest('form'),
                        postData = {
                                name : $('input[name="name"]', form).val(),
                                email : $('input[name="email"]', form).val(),
                                subject : $('input[name="subject"]', form).val(),
                                message : $('textarea[name="message"]', form).val(),
                                captcha : $('input[name="captcha"]', form).val()
                        };

                $.hp.doAction('contact', 'contact', postData, function(data) {
                        $.hp.dialogs.notify(data, 'Bericht verzonden');
                        $('input, textarea', form).val('');
                }, 'Onjuiste invoer');

                return false;
        });
        
     	$('#contact_name, #contact_email, #contact_password, #contact_subject').bind('keyup', function(e) {
                if(e.keyCode == 13) {
                        $('#contact_btn').click();
                }
        });

    
	$('body').prepend('<div id="jqDialog"></div>');
	$(document.body).click(function() {
	    $('#menu_help').hide();
	});

	 $('a#help').click(function(e) {
		   e.preventDefault();
		   
		   var $this = $(this),
		       offset = $this.offset(),
		       help = $('#menu_help');
		   
		   help.css({
			   left: offset.left - (help.width() / 2) + ($this.width() / 2) + 26,
			   top: offset.top + 8
		   });
		  			   
		   help.toggle();
		   e.stopPropagation();
	 });
	
	 $('#lost_password_btn').click(function(e){
		 e.preventDefault();
		 $('#menu_help').hide();
		 $.hp.dialogs.lostPassword();
		 return false;
	 });
	 
	 $('#logout_btn').click(function(e) {
		e.preventDefault();
		var $this = $(this),
			data = $this.data('logout');
		
		if(data) {
			return false;
		}
		
		$this.data('logout', true);
		$.hp.doAction('auth', 'logout');
	});
	 
	 $('#settings').bind('click', function(e) {
		e.preventDefault();
		$.hp.dialogs.settings();
	});

	$('#send-complaint-dialog').dialog({autoOpen: false, resizable: false, width: $.hp.popupWidth, modal: true, overlay: {opacity: 0.5, background: "black"}});
	$('#send-message-dialog').dialog({autoOpen: false, resizable: false, width: $.hp.popupWidth, modal: true, overlay: {opacity: 0.5, background: "black"}});
	$('#send-flirt-dialog').dialog({autoOpen: false, resizable: false, width: $.hp.popupWidth, modal: true, overlay: {opacity: 0.5, background: "black"}});

	$('.send-message-yes').live('click', function (evt) {
		evt.preventDefault();
		
		$('.err-subject-too-long, .err-msg-too-long').hide();
		
		if($('#send-message-dialog').find('#fld_subject').val().length > 250) {
			$('.err-subject-too-long').show();
			return;
		}

		if($('#send-message-dialog').find('#fld_message').val().length > 800) {
			$('.err-msg-too-long').show();
			return;
		}
		$(this).parent('form').submit();
	});

    $('.flirt').click(function (evt){
        evt.preventDefault();
        var to = $(this).attr('rel');
        $.get('/ajax/canflirt',{pid_to: to},function(data){
            var responseData = data.data;
            if ( responseData.status == 'yes' ) {
                $('#send-flirt-dialog').dialog('open');
                $('#send-flirt-dialog').find('.user_message_to').attr('value', responseData.to_info.profile_pid);
                var text = $('#send-flirt-dialog').find('.flirt-count-notification').html();
                $('#send-flirt-dialog').find('.flirt-count-notification').html(text.replace("#",responseData.message));
            } else {
                $('#'+responseData.message+'-dialog .message').attr('rel', responseData.to_info.profile_pid);
                var flirtError = $('#'+responseData.message+'-dialog .flirt-error').html();
                $('#'+responseData.message+'-dialog .flirt-error').html(flirtError.replace(/#to#/g,responseData.to_info.profile_name));
                $('#'+responseData.message+'-dialog').dialog({autoOpen: true, width:500, modal: true});
                $('#'+responseData.message+'-dialog').dialog('open');
            }
        },'json');
    });

    $('.profile_message').click( function(event) {
        event.preventDefault();
        if ( currentPage == 'profile' ) {
            psmfOpenSendMessage();
        } else {
            window.location = '/profile/'+$(this).attr('rel')+'/?sendmessage';
        }
    });

    $('#psmf_buy_credits_button').click( function(event) {
        event.preventDefault();
        document.location.href = '/credits?return='+continueMessageUrl;
    });

    $('#psmf_submit').click( function(event) {
        event.preventDefault();
		  $('#psmf_attachment').attr('disabled', '');
		  
        psmfFormSubmit();
    });

    $('.buy_credits_phone_button').click( function(event) {
        event.preventDefault();
        psmfHideCreditsError();
		  $('#psmf_attachment').attr('disabled', '');
        psmfFormSubmit();
    });

    $('.buy_credits_language_select').click( function(event){
        event.preventDefault();
        psmfChangeBuyCreditsLanguage($(this).attr('rel'));
    });

    /*$('.message').click(function (evt){
        evt.preventDefault();
        var className = $(this).hasClass('message')? 'message': 'flirt';
        var to = $(this).attr('rel');
        $("#send-"+className+'-dialog').dialog('open');
        $("#send-"+className+'-dialog').find('.user_message_to').attr('value', to);
        if(className == 'message')
        	$("#send-"+className+'-dialog').find('#fld_subject, #fld_message').attr('value', '');
    });*/
    
    $('.complain').click(function (evt){
        evt.preventDefault();
        var complaintPid = $(this).attr('rel');
        $('#send-complaint-dialog').dialog('open');
        $('#send-complaint-dialog').find('#complainPid').attr('value', complaintPid);
    });
    $('#password-dialog-sbmt').click(function (evt) {
    	evt.preventDefault();
    	
    	$('#password-dialog ._msg').html('');
    	$('#password-dialog ._err').html('');

    	if($('#fld_new_pass').val().trim().length < 6)
    		return $('#password-dialog ._err').html('Gebruik minimaal 6 tekens');

    	if($('#fld_new_pass').val().trim() != $('#fld_confirm_pass').val().trim())
    		return $('#password-dialog ._err').html('Foutieve invoer');
    	
		$.post('/ajax/profile', 
				{pass: $('#fld_new_pass').val().trim(), action: 'set_password'},
				function (data) {
					$('#password-dialog ._msg').html('Je nieuwe wachtwoord is opgeslagen.');
					$('#fld_new_pass').val('');
					$('#fld_confirm_pass').val('');
					setTimeout(function () {$("#password-dialog").dialog('close');}, 1000);
				},
				"json");
    });
    
    $('#settings').click(function (evt){
        evt.preventDefault();
        $("#settings-dialog").dialog('open');
    });

	$('select').each(updateSelect);
	
	// help menu
	$('#btn_snelzoeken').click(function (evt) {
		evt.preventDefault();
		
		var sz = $('#snelzoeken');
		if(sz.css('display') == 'none')
			sz.slideDown(300);
		else sz.slideUp(300);
	});
	
	if(jQuery().lightBox){
		$('.gallery').lightBox();
	}
	$('.show_gallery1').click(function (evt) {
		$('.gallery:first').click();
	});
	
	$(".addfavorite").click(function (evt) {
		evt.preventDefault();
		
		var p = $(this).parent();
		var favorite_uid = $(this).attr('rel');
		
		$.get('/ajax/profile', 
			{pid: favorite_uid , action: 'add_favorite'},
			function (data) {
				if($(p).find('.addfavorite').parent().hasClass('profile_link'))
					$(p).find('.addfavorite').parent().hide();
				else $(p).find('.addfavorite').hide();
			},
			"json");
	});
    
    $(".remfavorite").click(function (evt){
        evt.preventDefault();
        
        var favorite_uid = $(this).attr('rel');
        
    	$.get('/ajax/profile', 
    			{pid: favorite_uid , action: 'rem_favorite'},
    			function (data) {
    			    if(data.favorites_left==0){ 
    			     $("#no_favorites").css({display:'block'});
                    }
                    $("#fav_"+favorite_uid).remove();
    				 //$(p).find('.addfavorite').hide();
    			},
    			"json");        
    });
    $(".delete_photo").click(function (evt){
        evt.preventDefault();

        var del_img = $(this).attr('rel');
        var link_id = $(this).attr('id');
        var img_id  = link_id.replace('del_','');
        
        $("#"+img_id).remove();
        $("#del_"+img_id).remove();
        $("input[name="+img_id+"_current]").val('');        
        
        addToEnd = '<div class="foto_upload">'+$("input[name="+img_id+"_current]").parent(".foto_upload").html()+'</div>';
		$("input[name="+img_id+"_current]").parent(".foto_upload").remove();
		
        $("#photo_end").before(addToEnd);
        
    	$.get('/ajax/photo', 
			{img: del_img , action: 'rem_photo'},
			function (data) {				
				if(!data.deleted){
					alert('could not delete from disk!');
				}
			},
			"json");
    });
    
	// help menu
	$('.toggle_help').click(function (evt) {
		evt.preventDefault();
		$('#popup_menu_help').fadeIn(300);
	});
	$('.toggle_help_off').click(function (evt) {
		evt.preventDefault();
		$('#popup_menu_help').fadeOut(300);
	});
	
	if($('#error_cnt').length > 0) {
		var content = $.trim($('#error_cnt').html());
		if(content.length > 0) {
			$.hp.displayError(content);
		}
	}
});


