$(document).ready(function(){

	// --== Alert / Confirm Box

        function alert_msg(message) {
                $('#alertBox').modal({
                        containerId: ('modalAlertContainer'),
                        onShow: function (dialog) {
                                dialog.data.find('.message_alert').append(message);
                        }
                });
        }

        function confirm_msg(message, callback){
                $('#confirmBox').modal({
                        containerId: ('modalConfirmContainer'),
                        onShow: function (dialog) {
                                dialog.data.find('.message_confirm').append(message);

                                // if the user clicks "yes"
                                dialog.data.find('.modalConfirmYesImg').click(function () {
                                        // call the callback
                                        if ($.isFunction(callback)) {
                                                callback.apply();
                                        }
                                        // close the dialog
                                        $.modal.close();
                                });
                        }
                });
        }

	 // --== Open / Close Gemz Boxes
        $('#gNick .gHead, #gNeck .gHead, #gAcc .gHead, #gIwish .gHead, #gStory .gHead, #gSync .gHead, #gMsgs .gHead, #gMsgCodes .gHead').click(function() {
                var pID = $(this).parent().attr('id');
                $("#" + pID + ' > *.gCont').slideToggle(250);
                $("#" + pID + ' > *.coll,  ' + pID + ' > *.exp').slideToggle(250);
        });
        $('#gNick .gHead, #gNeck .gHead, #gAcc .gHead, #gIwish .gHead, #gStory .gHead, #gSync .gHead, #gMsgs .gHead, #gMsgCodes .gHead').hover(
                function() {
                        var pID = $(this).parent().attr('id');
                        $( '#' + pID + ' ' + ($('#' + pID + ' .gCont').css('display') == 'none' ? ' .closed' : ' .open')).show();
                },
                function() {
                        var pID = $(this).parent().attr('id');
                        $( '#' + pID + '  .open').hide();
                        $( '#' + pID + '  .closed').hide();
                }
        );
 
	// --== Editables
        $(".bffStory").editable(rpath + "ajax_handler.php", {
                type: 'textarea',
		rows: '5',
		select : true,
		cssclass: "bffStoryArea",
                //loadurl: "/ajax_handler.php?action=get_bff_story",
                submit: "save",
                cancel: "cancel",
                indicator : "<img src='" + rpath + "images/indicator.gif'>",
                tooltip   : 'Click to edit...'
        });
	
	$("#change_nick").editable(rpath + "ajax_handler.php", {
		submit: "save",
		cancel: "cancel",
                indicator : "<img src='" + rpath + "images/indicator.gif'>",
                tooltip   : 'Click to edit...'
	});
	

	// The following function vars represent "re-triggers" for some of the functionalities
	// Otherwise the newly generated DOM elements by AJAX won't handle events properly / at all
	var reFavorite = function(parentElId) {
		var pref = '';
		if(parentElId) {
			pref = '#' + parentElId + ' ';
		}
		$(pref + ".favorites").editable(rpath + "ajax_handler.php", {
			submit: "save",
			cancel: "cancel",
			indicator : "<img src='" + rpath + "images/indicator.gif'>",
			tooltip   : 'Click to edit...',
			style: "width:100%;"
		});
		$(pref + '.favorites_remove').click(function() {
			var ac = $(this).attr('id');
			confirm_msg ("Are you sure to remove the item?", function(){
				$.ajax({
					type: 'POST',
					dataType: 'json',
					url:rpath + 'ajax_handler.php',
					data: {id: ac},
					success: function(data) {
						if(data.success == 1) {
							$('#' + ac).parent().parent().remove();
						} else 
							alert_msg('There was an error while removing the favorite!');
					}, 
					error: function() {
						alert_msg('There was an error while removing the favorite!');
					}
				});
			});
		});
	}

	var showMessageInbox = function(){
        // -== Show All Message manipulation:
		// Show received messages:
		$('.subject, .message').click(function(){
			var cid = $(this).attr('id').replace(/(.*)-(.*)/, '$2');
			var doit = 0;
			if($('#inboxTbl #message_content-' + cid + '').css('height') == '12px') doit = 1;
			$('#inboxTbl  .subject').css('white-space', 'nowrap');
			$('#inboxTbl .message').css('height', '12px');

			if(doit) {
				$('#inboxTbl #message_content-' + cid + '').css('height', '100%');
				$('#inboxTbl  #message_subject-' + cid + '').css('white-space', 'normal');
			}
		
		});

		// Reply:
		$('div.reply span').click(function(){
			compose_reset();
			$("#gInboxTab").removeClass('act');
			cid = 'gCompose';
			$('.gMsgCnt').each(function(i, s) {
				$(s).removeClass('act');
			});

			$('#' + cid + 'Cnt').addClass('act');
			$('#' + cid + 'Tab').addClass('act');
			var mid = $(this).attr('id');
			mid = mid.replace(/reply_message-/, '');
			var sid = $("tr#message_row-" + mid + ' span.sender_id').attr('id');
			sid = sid.replace(/message_sender_id-/, '');
			$('#compose_to_friends').append($('#compose_friend_id-' + sid));
			var msub = $('#message_subject-' + mid).html();
			$("#compose_subject").attr('value', 'Re:' + msub);
			$("#compose_message").focus();
		});

		// Remove message:
		$('.message_remove').click(function(){
			var mid = $(this).attr('id').replace(/remove_message-/, '');
			var dataid = $(this);
			confirm_msg ("Are you sure to remove the item?", function(){
				$.ajax({
					type: 'POST',
					dataType: 'json',
					url:rpath + 'ajax_handler.php',
					data: {id: dataid.attr('id')},
					success: function(data) {
						if(data.success == 1) {
							$('#message_row-' + mid).remove();
						}
						alert_msg(data.msg);
					},
					error: function() {
						alert_msg('There was an error while deleting the message!');
					}
				});
			});
		});
	}	
	
	showMessageInbox();

	var addMCHandler = function(parentElId) {
		var pref = '';
		if(parentElId) {
			pref = '#' + parentElId + ' ';
		}
		
		$(pref + ".editable").editable(rpath + "ajax_handler.php", {
			submit: 'save',
			cancel: "cancel",
			indicator : "<img src='" + rpath + "images/indicator.gif'>",
			tooltip   : 'Click to edit...'
		});
		
		$(pref + '.clpickBtn').each(function() {
			var eid = $(this).attr('id');
			var clr = $('#' + eid + ' div').css('background-color');
			$("#" + eid).ColorPicker({
				color: clr,
				onShow: function (colpkr) {
					$(colpkr).slideToggle(500);
					return false;
				},
				onHide: function (colpkr) {
					$(colpkr).slideToggle(500);
					return false;
				},
				onSubmit:function(hsb, hex, rgb) {
					$.ajax({
						type: 'POST',
						dataType: 'json',
						url:rpath + 'ajax_handler.php',
						data: {id: eid, value: hex},
						success: function(data) {
							if(data.success == '1') {
								$('#' + eid + ' div').css('background-color', '#' + hex);
							} else {
								alert_msg(data.msg);
							}
						}, 
						error: function() {
							alert_msg('There was an error while saving the color!');
						}
					});
				}
			});
		});
		$(pref + '.removeMessageCode').click(function() {
			var ac = $(this).attr('id');
			confirm_msg ("Are you sure to remove the item?", function(){
				$.ajax({
					type: 'POST',
					dataType: 'json',
					url:rpath + 'ajax_handler.php',
					data: {id: ac},
					success: function(data) {
						if(data.success == 1) {
							$('#' + ac).parent().parent().remove();
						} else 
							alert_msg('There was an error while removing the message code<s>!');
					}, 
					error: function() {
						alert_msg('There was an error while removing the message code!');
					}
				});
			});
		});
	}

	$('.ffNick').click(function() {
		$('#ajaxCnt').hide();
		var offs = $(this).offset({ border: true, padding: true, margin:true });
		offs.left -= 10;
		offs.top += 10;
		$('#ajaxCnt').css(offs);
		$('#ajaxCnt #aCnt').hide();
		$('#ajaxCnt').show();
		$('#ajaxCnt .ajaxLoader').show();
		$.ajax({
			type: 'POST',
			dataType: 'json',
			url:rpath + 'ajax_handler.php',
			data: {id:$(this).attr('id')},
			success: function(data) {
				if(data.success == '1') {
					$('#ajaxCnt #aCnt').html(data.html);
					$('#ajaxCnt #aCnt').show();
					$('#ajaxCnt .ajaxLoader').hide();
					$('#ajaxCnt').show();
				} 
			},
			error: function() {
				alert_msg('There was an error while fetching friends info!');
			}
		});
		$('#ajaxCnt').get(0).focus();
	});

	$('#ajaxCnt').blur(function() {
		$('#ajaxCnt #aCnt').html('');
		$('#ajaxCnt').hide();
	});
	$('#ajaxCnt dt').click(function(){
		$('#ajaxCnt').hide();
	});
	
	$('#show_all').click(function() {
		$.ajax({
			type: 'POST',
			dataType: 'json',
			url:rpath + 'ajax_handler.php',
			data: {id: 'show_all_messages'},
			success: function(data) {
				if(data.success == '1') {
					$('#gInboxCnt').html(data.html);
					showMessageInbox();
				} 
			},
			error: function() {
				alert_msg('There was an error while fetching show_all_messages info!');
			}
		});
		return false;
	});	

	var req_read = function() {
                var mid = $(this).attr('id').replace(/(.*)-(.*)/, '$2');
		$.ajax({
			type: 'POST',
			dataType: 'json',
			url:rpath + 'ajax_handler.php',
			data: {id: "read_message-" + mid},
			success: function(data) {
				if(data.success == 1) {
					// Remove req_read from the specifiv message:
					$(".req_read").each(function(){
						if($(this).attr('id') == 'message_subject-' + mid || $(this).attr('id') == 'message_content-' + mid) {
							$(this).removeClass("req_read");
							$(this).unbind("click", req_read);
						}
					});
				} 
			} 
		});
	};
	$('.req_read').click(req_read);

	$('#add_message_code').click(function() {
		$.getJSON(rpath + 'ajax_handler.php?action=add_message_code', function(data) {
			$('#clpkTab').children('tbody').append(data.row);
			// Define event handlers for the newly AJAX generated DOM elements
			addMCHandler(data.id);
		});
	});
	
	$('#add_favorite').click(function() {
		$.getJSON(rpath + 'ajax_handler.php?action=add_favorite', function(data) {
			$('#favTab').children('tbody').append(data.row);
			// Define event handlers for the newly AJAX generated DOM elements
			reFavorite(data.id);
		});
		return false;
	});

	addMCHandler();
	reFavorite();

	// --== Theme Changer:
	$('#gemzThemeChanger span').click(function() {
		var thm = $(this).attr('id').replace(/change_theme-/, '');
		if($('#cx').hasClass(thm)) 
			return;
		else {
			$.ajax({
				type: 'POST',
				dataType: 'json',
				url:rpath + 'ajax_handler.php',
				data: {id:'change_theme-' + thm},
				success: function(data) {
					if(data.success == '1') {
						$('#cx').removeClass('none');
						$('#cx').removeClass('gemzbg1');
						$('#cx').removeClass('gemzbg2');
						$('#cx').removeClass('gemzbg3');
						$('#cx').addClass(thm);
					} 
				},
				error: function() {
					alert_msg('There was an error while changing the theme!');
				}
			});
		}
	});

	// --== Reorder / Sort Boxes:	
	var preventDoubleSortCall = 0;
	var initSort = function() {preventDoubleSortCall = 0;}
	var reorderBoxes = function() {
		 $.ajax({
			type: 'POST',
			dataType: 'json',
			url:rpath + 'ajax_handler.php',
			data: {action:'reorderboxes', l:$('#glc').sortable("toArray").toString(), r:$("#grc").sortable("toArray").toString()},
			success: function(data) {
				if(data.success == '1') {
				
				} else {
					//alert_msg('There was an error while reordering boxes!');
				}
			},
			error: function() {
				alert_msg('There was an error while reordering boxes!');
			}
		});
	}
	
	// Prevent initiating sort request while we do actual sorting
	var repositionBoxes = function() {
		if(!preventDoubleSortCall) reorderBoxes();
		preventDoubleSortCall = 1;
	}
	// -== Reorder / Sort Profile Box:
	$("#glc").sortable({connectWith:["#grc"],revert:"invalid",cursor:"move",opacity:0.75,forcePlaceholderSize:true,start:initSort,update:repositionBoxes, containment: '#main', placeholder: 'sortplaceholder', handle:'div.sorthelper'}); 
	$("#grc").sortable({connectWith: ["#glc"], revert:"invalid",cursor:"move",opacity:0.75,forcePlaceholderSize:true,start:initSort,update:repositionBoxes, containment: '#main', placeholder: 'sortplaceholder', handle: 'div.sorthelper'});
	
	// -== Drag / Drop friends "To"
	$('#compose_all_friends').sortable({connectWith:['#compose_to_friends'], revert:"invalid", cursor:"move",opacity:0.75,forcePlaceholderSize:true, placeholder:'sortplaceholder'});
	$('#compose_to_friends').sortable({connectWith:['#compose_all_friends'], revert:"invalid", cursor:"move",opacity:0.75,forcePlaceholderSize:true, placeholder:'sortplaceholder'});

	// --== Open / Close Chat
/*	var chatOpened = 0;
	$('#chat').click(function(){
		if(!chatOpened) {
			chatOpened = 1;
			$('#chatFrm iframe').attr('src', '/chat.php');
		}
		$('#ajax_chat').slideToggle(650);
	});
	$('#chatClose').click(function() {
		$('#chatFrm iframe').attr('src', '/dummy.html');
		chatOpened = 0;
		$('#ajax_chat').slideUp(650);
	});	*/
	
	// --== Change Avatar
	$('#changeAvatar, .closeAvatar').click(function() {
		$('#avatarSel').slideToggle(500);
	});
	
	$('.avatarChange').click(function() {
		var act = $(this).attr('id');
		$('#avatarSel').slideUp(500);
		$.ajax({
			type: 'POST',
			dataType: 'json',
			url:rpath + 'ajax_handler.php',
			data: {id: act},
			success: function(data) {
				if(data.success == 1) {
					$('#avatarImg').attr('src', data.img);
					$('#avatarImg').attr('alt', data.alt);
					$('#avatarImg').attr('title', data.title);
				} else 
					alert_msg('There was an error while changing the avatar!');
			}, 
			error: function() {
				alert_msg('There was an error while changing the avatar!');
			}
		});
	});
	
	// --== Send // Compose Message:
	var compose_reset = function() {
		$('#composefrm').get(0).reset();
		$('#compose_to_friends').html('');
		$('#compose_all_friends').html('');
		$(user.friends).each(function(i, s){
			if(user.friends[i] != undefined);
			$('#compose_all_friends').append('<div class="compose_friend" id="compose_friend_id-' + s.friend_id + '">' + s.nickname + '</div>');
		});
		return false;
	}
	$('#compose_cancel').click(compose_reset);
	
	var encode_friends = function() {
		var fr = '';
		$('#compose_to_friends div').each(function(i, s){
			fr = fr + ($(s).attr('id').replace(/compose_friend_id-/, '')) + '|';
		});
		if(fr != '') 
			fr = fr.substr(0, fr.length - 1);
		return fr;
	}
	$('#compose_send').click(function() {
		// validate:
		if($('#compose_to_friends div').length < 1) {
			alert_msg('Select friends you want to send this message to!');
			return;
		}
		if($.trim($('#compose_message').get(0).value) == '') {
			alert_msg('Enter your message!')
			return;
		}
		
		// Send:
		// The AJAX handler expects id and value as POST vars so we'll encode the request data:
		// id --> "send_message-{friends|ids|to|send|the|message|to}(#^#^#)subject"; value --> "message"
		$.ajax({
                        type: 'POST',
                        dataType: 'json',
                        url:rpath + 'ajax_handler.php',
                        data: {id: 'send_message-' + encode_friends() + '(#^#^#)' + ($('#compose_subject').get(0).value), value: $('#compose_message').get(0).value},
                        success: function(data) {
                                if(data.success == 1) 
					compose_reset();
				alert_msg(data.msg);
                        },
                        error: function() {
				alert_msg('There was an error while sending the message!');
                        }
                });
	});
	
	// Remove message:
	$('.message_remove').click(function(showMessageInbox){
	});

	// Remove Sent message:
	$('.sent_message_remove').click(function(){
		var mid = $(this).attr('id').replace(/remove_sent_message-/, '');
		$.ajax({
                        type: 'POST',
                        dataType: 'json',
                        url:rpath + 'ajax_handler.php',
                        data: {id: $(this).attr('id')},
                        success: function(data) {
                                if(data.success == 1) {
					$('#message_row-' + mid).remove();
				}
				alert_msg(data.msg);
                        },
                        error: function() {
				alert_msg('There was an error while deleting the message!');
                        }
                });
	});
	
	// Remove from cart / accessories:
	$('.gemz_cart_remove').click(function(e){
		var mid = $(this).attr('id').replace(/remove_sent_message-/, '');
		var par = $(this).parents('tr');
		var dataid = $(this);
		confirm_msg ("Are you sure to remove the item?", function(){
			$.ajax({
				type: 'POST',
				dataType: 'json',
				url:rpath + 'ajax_handler.php',
				data: {id: dataid.attr('id')},
				success: function(data) {
					if(data.success == 1) {
						par.remove();
					}
					alert_msg(data.msg);
				},
				error: function() {
					alert_msg('There was an error while removing the item from the cart!');
				}
			});
		});
	});
	
	// Remove from wishlist:
	$('.gemz_wishlist_remove').click(function(){
		var mid = $(this).attr('id').replace(/remove_sent_message-/, '');
		var par = $(this).parents('tr');
		var dataid = $(this);
		confirm_msg ("Are you sure to remove the item?", function(){
			$.ajax({
				type: 'POST',
				dataType: 'json',
				url:rpath + 'ajax_handler.php',
				data: {id: dataid.attr('id')},
				success: function(data) {
					if(data.success == 1) {
						par.remove();
					}
					alert_msg(data.msg);
				},
				error: function() {
					alert_msg('There was an error while removing the item from the wishlist!');
				}
			});
		});
	});
        // --== Gemz Messages:
        // Tabs:
        $('.gTab').click(function(){
                if($(this).hasClass('act')) return;
		compose_reset();
                var cid = $(this).attr('id').replace(/Tab/, '');
                cid = cid.replace(/Tab/, '');
                $('.gTab').each(function(i, s) {
                        $(s).removeClass('act');
                });
                $('.gMsgCnt').each(function(i, s) {
                        $(s).removeClass('act');
                });
                $(this).addClass('act');
                $('#' + cid + 'Cnt').addClass('act');
        });
        // Reply:
        $('div.reply span').click(function(showMessageInbox){
        });
        // -== Message manipulation:
        // Show received messages:
        $('.subject, .message').click(function(showMessageInbox){
        });

        // Show sent messages:
        $('.sent_subject, .sent_message').click(function(){
                var cid = $(this).attr('id').replace(/(.*)-(.*)/, '$2');
                var doit = 0;
                if($('#sentTbl #sent_message_content-' + cid + '').css('height') == '12px') doit = 1;
                $('#sentTbl  .sent_subject').css('white-space', 'nowrap');
                $('#sentTbl .sent_message').css('height', '12px');

                if(doit) {
                        $('#sentTbl #sent_message_content-' + cid + '').css('height', '100%');
                        $('#sentTbl  #sent_message_subject-' + cid + '').css('white-space', 'normal');
                }
        });

});
