var x1=0, x2=130, y1=0, y2=162, w=130, h=162, photoIdName, curWidth, curHeight;
var uploadError=false;
var photoName;
var addressContentScroll, aboutContentScroll;
var isPhotoShown = 1, isPhoto; 
var editCB;
var stateChanged = 0;
var camera;
var canvas;

var pos = 0;
var ctx = null;
var cam = null;
var image = null;

var filter_on = false;
var filter_id = 0;
var progressBar;
var loadGalleryFunction;
var xCounter = 1;
var refreshScroller;
var camera_dialog;

var oldItem = new Array();

var addressWysiwyg;

var loadedCats = new Array();
function print_r(o)
{
    function f(o, p, s)
    {
        for(x in o)
        {
            if ('object' == typeof o[x])
            {
                s += p + x + ' obiekt: \n';
                pre = p + '\t';
                s = f(o[x], pre, s);
            }
            else
            {
                s += p + x + ' : ' + o[x] + '\n';
            }
        }
        return s;
    }
    return f(o, '', '');
}

function preview(img, selection) {
    if (!selection.width || !selection.height)
        return;

   // var newImage = document.getElementById('photoEdit');
    var scaleX = 130 / selection.width;
    var scaleY = 162 / selection.height;

    $('#preview img').css({
        width: Math.round(scaleX * img.width),
        height: Math.round(scaleY * img.height),
        marginLeft: -Math.round(scaleX * selection.x1),
        marginTop: -Math.round(scaleY * selection.y1)
    });

    x1 = selection.x1;
    y1 = selection.y1;
    x2 = selection.x2;
    y2 = selection.y2;
    w = selection.width;
    h = selection.height;
	curWidth = img.width;
	curHeight = img.height;	
}

jQuery(document).ready(function($){
	$( "#dialog:ui-dialog" ).dialog( "destroy" );
	$('#status').fadeOut();
	
	var yourname = $( "#yourname" ),
		youremail = $( "#youremail" ),
		yourmsg = $( "#yourmsg" ),
		id = $( "#id" ),
		allFields = $( [] ).add( yourname ).add( youremail ).add( yourmsg ),
		tips = $( ".validateTips" ),
		err1 = $("#t_err1").val(),
		err2 = $("#t_err2").val(),
		yourname2 = $( "#yourname2" ),
		youremails = $( "#youremails" ),
		yourmsg2 = $( "#yourmsg2" ),
		allFields2 = $( [] ).add( yourname2 ).add( youremails ).add( yourmsg2 ),
		tips2 = $( ".validateTips2" );

	var stateChangedFun = function() {
			isEdited = editCB.attr('checked');
			if (isEdited && !stateChanged )
			{  	
				if(isFirstVisit) {
				$('.wizardTip').show();
				$('#tipEditStart').addClass('tipEditStop');
				$('#dockicons').addClass('wizardTipDock');
				}
				var text = $("#aboutText").val();
				var addressText = $("#addressText").val();
				var lang = $("#lang").val();
				var display_name = $("#displayName").text();
				var position = $("#position").text();
				var phone = $("#phone").text();
				var fax = $("#fax").text();
				loadedCats = new Array();
				//$("#photo").html('<noscript>'+trans['javascript']+'</noscript>');		
				createUploader();
				$('#cameraOpen').show();
				$('#switchPhoto').show();			
				if($('#photo img').attr('src')) {
					$('#removePhoto').show();
					//photoName = ($('#photo img').attr('src'));
				}
				//$("#photo_up").html($("#photo_up").html()+'<div id="removePhoto">Remove</div>');
				$("#about").html('<div><h4>'+$("#t_about").val()+'</h4><textarea id="wysiwyg" cols="30" rows="8">'+text+'</textarea></div>');
				var phoneFax = '<input type="text" name="phoneText" id="phoneText" value="'+phone+'"/><input type="text" name="faxText" id="faxText" value="'+fax+'"/>';
				$("#address").html('<div><h4>'+$("#t_address").val()+'</h4><textarea id="wysiwyg_address" cols="30" rows="5">'+addressText+'</textarea>'+phoneFax+'</div>');
				$("#phoneText").focusout(
					function() {
						savePhone();
					});	
				$("#faxText").focusout(
					function() {
						saveFax();
					});	

				$("#displayName").html('<input type="text" name="displayNameText" id="displayNameText" value="'+display_name+'"/>');
					$("#displayNameText").focusout(
					function() {
						saveName();
					});
				$("#position").html('<input type="text" name="positionText" id="positionText" value="'+position+'"/>');
					$("#positionText").focusout(
					function() {
						savePosition();
					});				
				$("#dockicons").append('<li class="dock-item2 glossy" id="addNewIcon"><a class="" href="#" id="new-icon" onClick="displaySocials();return false;"><span>'+trans['add_new_services']+'</span><img src="//beename.com/lib/profile/css-dock-menu/images/icons/addnew.png" alt="'+trans['add_new_services']+'"/></a></li>');	
				startDockMenu();

				$('#wysiwyg').wysiwyg({
					i18n: lang,
					css: '//beename.com/css/profile/editor_about.css',			
					removeHeadings: true,
				    controls: {
				        insertImage: { visible : false },
				        insertTable: { visible : false },
				        createLink: { visible : true },
				        indent: { visible : false },
				        outdent: { visible : false },
				        removeFormat: { visible : false },
				        undo: { visible : false },
				        redo: { visible : false },
				        insertHorizontalRule: { visible : false },
				        subscript: { visible : false },
				        superscript: { visible : false },
				        h1: { visible : false },
				        h2: { visible : false },
				        h3: { visible : false },
				        increaseFontSize: { visible : true },
				        decreaseFontSize: { visible : true }
				    }
				});
				addressWysiwyg = $('#wysiwyg_address').wysiwyg({
					i18n: lang,
					css: '//beename.com/css/profile/editor.css',
					removeHeadings: true,
				    controls: {
				        insertImage: { visible : false },
				        insertTable: { visible : false },
				        createLink: { visible : true },
				        indent: { visible : false },
				        outdent: { visible : false },
				        removeFormat: { visible : false },
				        undo: { visible : false },
				        redo: { visible : false },
				        insertHorizontalRule: { visible : false },
				        subscript: { visible : false },
				        superscript: { visible : false },
				        h1: { visible : false },
				        h2: { visible : false },
				        h3: { visible : false },
				        increaseFontSize: { visible : false },
				        decreaseFontSize: { visible : false },
						insertOrderedList: { visible : false },
						insertUnorderedList: { visible : false }
				    }
				});
	
								
				oldItem['name'] = $("#displayNameText").val();
				oldItem['position'] = $("#positionText").val();
				oldItem['phone'] = $("#phoneText").val();				
				oldItem['fax'] = $("#faxText").val();
				$.ajax({
		    		type: "POST",  
		    		url: "//beename.com/profile/GetGallery",
		    		data: "getGallery=1",
		    		/*async: false,*/
		    		success: function(server_response)
		    		{
		    				if(server_response)
		    				{
								$("#galleryContent").html(server_response).ready(function(){
													$.getScript('http://beename.com/lib/profile/gallery/gallery.js', function() {
															$("#outer_container").show();
															$('#arrow_indicator').show();
															createWallpaperUploader();
                                                            $( "#accordion" ).accordion({
                                                                autoHeight: false, 
                                                                collapsible: true,
                                                                active: false,
                                                                change: function() {
$dragger.css("top",0); //reset content scroll
							                                            //$customScrollBox_container.css("top",0);
							                                            $customScrollBox.unbind("mousewheel");
							                                            refreshScroll();
                                                                },
                                                                changestart: function(event, ui) {
                                                                	var catName = ui.newHeader.attr("id");
                                                                	if(loadedCats[catName] == true)
                                                                	{	
                                                                		return;
                                                                	}
                                                                	$("#"+catName+"Content").html('<div class="catLoading"><img src="http://beename.com/images/loader.gif" align="absmiddle">'+$("#t_loading").val()+'...</div>');                                                                				

                                                                	$.ajax({
                                                                        type: "POST",  
                                                                        url: "//beename.com/profile/GetCategory",
                                                                        data: "category="+catName,
                                                                        success: function(server_response)
                                                                        {
	                                                                                                                                                     																		if(server_response)
	                                                                        {
																			$("#"+catName+"Content").html('<div class="catLoading"><img src="http://beename.com/images/loader.gif" align="absmiddle">'+$("#t_loading").val()+'...</div><div class="galleryItems" style="display: none">'+server_response+'</div>').ready(function(){
																					var $wallpaperGalleryCat = $("#"+catName+"Content");
																					var $wallpapersCat	= $wallpaperGalleryCat.find('img');
																					var cnt_imagesCat		= $wallpapersCat.length;
																					var loadedCat			= 0;
																					//preload all the images in the book,
																					//and then call the booklet plugin
			
																					$wallpapersCat.each(
																					function(){
																						var $imgCat 	= $(this);
																						var source	= $imgCat.attr('src');
																						$imgCat.load(
																						function(){
																							++loadedCat;
																							if(loadedCat == cnt_imagesCat) {
																							loadedCats[catName] = true;																																					$.getScript('http://beename.com/lib/profile/gallery/gallery.js', function() {
																												                                                                																															                                                                    $("#"+catName+"Content .catLoading").hide();
							                                                                    $("#"+catName+"Content .galleryItems").show();
							                                                                    $dragger.css("top",0); //reset content scroll
							                                                                    //$customScrollBox_container.css("top",0);
							                                                                    $customScrollBox.unbind("mousewheel");
							                                                                    refreshScroll();

																																																												}); //eof getScript
																							}
																						});   
	                                                                    			});
																				});
	                                                                        }  //eof server response if
                                                                            else {
                                                                            							                                                                    $("#"+catName+"Content .catLoading").html(trans['no_images']);

                                                                            }
                                                                           
                                                                        } //eof success 
                                                                    });// end of ajax

                                                                }//end of changestart
                                                            });//end of accordion
															refreshScroll();
													});//end of get script
																								
								});
		
		    				}  
		    				else if(server_response == '0')
		    				{  
                                $('#growl').growlAlert('show', { content: $("#t_error").val(), title:$("#t_not_sent").val(), position:'top-right', delayTime: 4000 });
								$('#status').fadeOut('slow');

		    				}

		    		}
		    		 
		    	});

				stateChanged = 1;
			}
			if(!isEdited && stateChanged) //save
			{
                userId = $("#id").val();
				if(isFirstVisit) {
                if (userId != 2) displayPromoteBox();
				$('.wizardTip').hide();
				$('#tipEditStart').hide();
				$('#dockicons').removeClass('wizardTipDock');
				isFirstVisit = false;
				}
				saveForm(false);
				$('#cameraOpen').hide();
				if($('#photo img').attr('src'))
					isPhoto = 1;
				else
					isPhoto = 0;

				if(!isPhotoShown)
				{
					$('.viewport').css('width', 385);
					addressContentScroll.tinyscrollbar_update();
					aboutContentScroll.tinyscrollbar_update();
				}
				else
				{
				$('.viewport').css('width', 225);
				addressContentScroll.tinyscrollbar_update();
				aboutContentScroll.tinyscrollbar_update();
				}
				if(!isPhoto)
				{
//					alert('dupa');
					hidePhoto();
				}
				else if(isPhotoShown)
				{
					$('#photo').css('margin-left', 0);
					$('#card_content, #scrollBar1').css('width', 240);
					$('.viewport').css('width', 225);
					$('#switchPhoto').removeClass('switchShow');
				}
				$('#removePhoto').hide();
				$('#switchPhoto').hide();	

				$("#outer_container").hide();
				$('#arrow_indicator').hide();
				$("#galleryContent").html('');
				$("#galleryScript").remove();


				stateChanged = 0;			
			}
		}
	
	$('.iPhoneCheckContainer').bind('change', stateChangedFun);
	
	$( "#dialog-form" ).dialog({
		autoOpen: false,
		height: 400,
		width: 500,
		modal: true,
		resizable: false,
		buttons: {
			"Send message": function() {
				var bValid = true;
				allFields.removeClass( "ui-state-error" );

				bValid = bValid && checkLength( yourname, "your name", 3, 20);
				bValid = bValid && checkLength( youremail, "e-mail", 6, 80 );
				bValid = bValid && checkLength( yourmsg, "message", 10, 255 );
				bValid = bValid && checkRegexp( yourname, /^[a-z]([0-9a-z_" "])+$/i, err1+"." );
				// From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
				bValid = bValid && checkRegexp( youremail, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, err2+"." );

				if ( bValid ) {
					$.ajax({
			    		type: "POST",  
			    		url: "/profile/SendMessage",
			    		data: "name="+yourname.val()+"&email="+youremail.val()+"&msg="+yourmsg.val()+"&id="+id.val(),
			    		success: function(server_response)
			    		{
							$('#status').fadeIn('slow');
							$("#status").html($("#t_sending").val()+'...');
			    			$("#status").ajaxComplete(function(event, request)
			    			{
			    				if(server_response == '1')
			    				{
                                    $('#growl').growlAlert('show', { content: trans['message_sent'], title:$("#t_sent").val(), position:'top-right', delayTime: 4000 });
			    				}  
			    				else if(server_response == '0')
			    				{  
                                    $('#growl').growlAlert('show', { content: $("#t_error").val(), title:$("#t_not_sent").val(), position:'top-right', delayTime: 4000 });
			    				}
								setTimeout(fade_out, 5000);
			    			});
			    		} 
			    	});
					$( this ).dialog( "close" );
				}
			},
			Cancel: function() {
				$( this ).dialog( "close" );
			}
		},
		close: function() {
			allFields.val( "" ).removeClass( "ui-state-error" );
		}
	});

	$( "#share-dialog-form" ).dialog({
		autoOpen: false,
		height: 400,
		width: 500,
		modal: true,
		resizable: false,
		buttons: {
			"Send message": function() {
				var bValid = true;
				allFields2.removeClass( "ui-state-error" );
				
				bValid = bValid && checkLength( yourname2, "your name", 3, 20);
				bValid = bValid && checkLength( youremails, "e-mail addresses", 6, 200 );
				bValid = bValid && checkLength( yourmsg2, "message", 10, 255 );
				bValid = bValid && checkRegexp( yourname2, /^[a-z]([0-9a-z_" "])+$/i, err1+"." );

				if ( bValid ) {
					$.ajax({
			    		type: "POST",  
			    		url: "//beename.com/profile/SendMessage2",
			    		data: "name="+yourname2.val()+"&emails="+youremails.val()+"&msg="+yourmsg2.val()+"&id="+id.val(),
			    		success: function(server_response)
			    		{
							$('#status').fadeIn('slow');
							$("#status").html($("#t_sending").val()+'...');
			    			$("#status").ajaxComplete(function(event, request)
			    			{
			    				if(server_response == '1')
			    				{
                                    $('#growl').growlAlert('show', { content: trans['message_sent'], title:$("#t_sent").val(), position:'top-right', delayTime: 4000 });
			    				}  
			    				else if(server_response == '0')
			    				{  
                                    $('#growl').growlAlert('show', { content: $("#t_error").val(), title:$("#t_not_sent").val(), position:'top-right', delayTime: 4000 });
			    				}
								setTimeout(fade_out, 5000);
			    			});
			    		} 
			    	});
					$( this ).dialog( "close" );
				}
			},
			Cancel: function() {
				$( this ).dialog( "close" );
			}
		},
		close: function() {
			allFields.val( "" ).removeClass( "ui-state-error" );
		}
	});


	$( "#icon-select-form" ).dialog({
		autoOpen: false,
		modal: true,
		width: 980,
		height: 550,
		resizable: false,		
		buttons: {
			Ok: function() {
				var form = $("#add_form");
				$.ajax({
		    		type: "POST",  
		    		url: "//beename.com/profile/SaveServices",
		    		data: form.serialize(),
		    		success: function(server_response)
		    		{
						$('#status').fadeIn('slow');
						$("#status").html('<img src="http://beename.com/images/loader.gif" align="absmiddle">'+$("#t_saving").val()+'...');
		    				if(server_response)
		    				{
								$('#dockicons').html(server_response);
								$("#dockicons").append('<li class="dock-item2 glossy" id="addNewIcon"><a class="" href="#" id="new-icon" onClick="displaySocials();return false;"><span>'+trans['add_new_services']+'</span><img src="http://beename.com/lib/profile/css-dock-menu/images/icons/addnew.png" alt="'+trans['add_new_services']+'"/></a></li>');		
								startDockMenu();
								$('#growl').growlAlert('show', { content: trans['profile_saved'], title:$("#t_saved").val(), position:'top-right', delayTime: 4000 });		    				
							}  
		    				else if(server_response == '0')
		    				{  
								$('#growl').growlAlert('show', { 	content: trans['profile_not_saved'], title: $("#t_error").val(), position:'top-right', delayTime: 4000 });		    				
							}
						$('#status').fadeOut('slow');
		    		} 
		    	});
				$( this ).dialog( "close" );
				return false;
			}
		}
	});
	
	$( "#crop-image" ).dialog({
		autoOpen: false,
		modal: true,
		width: 800,
		heigth: 600,
		resizable: false,
		buttons: {
			Ok: function() {
				$('.imgCrop').remove();
				var postData = "x1="+x1+"&x2="+x2+"&y1="+y1+"&y2="+y2+"&w="+w+"&h="+h+"&photoIdName="+photoIdName+"&curWidth="+curWidth+"&curHeight="+curHeight;
				/* save */
				$.ajax({
			    	type: "POST",
			    	url: "//beename.com/profile/cropImage",
		    		data: postData,
			    	success: function(server_response)
			    	{
						$("#photo").html('<img alt="'+name+'" title="'+name+'" src="http://beename.com/images/avatar/'+$('#id').val()+'_'+photoName+'?'+(Math.random()*1000001)+'" />');
						$('#removePhoto').show();
 			    	}
			    });
				$( this ).dialog( "close" );
				saveForm(true);
			}
		},
		close: function() {$('.imgCrop').remove();},
		dialogClass: 'crop_image_dialog'
	});
	
	$( "#cameraParent" ).dialog({
		autoOpen: false,
		modal: true,
		width: 290,
		heigth: 400,
		resizable: false,
		buttons: {
			Save: function() {
				$('#status').fadeIn('slow');
				$("#status").html('<img src="http://beename.com/images/loader.gif" align="absmiddle">'+$("#t_saving").val()+'...');				
				$('#countDown').html('');	
				$('.mp3').html('');
				$('#takeNew').hide();	
				$('#camera').html('');
				$('#canvasWrapper').hide();
				$('#canvasWrapper').css('margin-top','0');
				try{
				var dataUrl = canvas.toDataURL();
				}
				catch(e) {
					alert(trans['photo_error']);
				}
				if(dataUrl) {
					$.ajax({
			    		type: "POST",
			    		url: "//beename.com/profile/uploadCameraPhoto",
		    			data: "imageData="+dataUrl,
			    		success: function(server_response)
			    		{
								if(server_response)
								{
                                photoName = 'avatar.png';
								$("#photo").html('<img alt="'+name+'" title="'+name+'" src="http://beename.com/images/avatar/'+$('#id').val()+'_'+photoName+'?'+Math.floor(Math.random()*1000001)+'" />');
								$('#removePhoto').show();
								$('#status').fadeOut('slow');				 			    		
								$('#growl').growlAlert('show', { content: trans['profile_saved'], title:$("#t_saved").val(), position:'top-right', delayTime: 4000 });
								}
								else
									$('#growl').growlAlert('show', { 	content: trans['profile_not_saved'], title: $("#t_error").val(), position:'top-right', delayTime: 4000 });
				
						}
			    	});
				}
			
				$( this ).dialog( "close" );				
			}
		},
		close: function() {	
			$('#countDown').html('');
				$('#takeNew').hide();			
			$('.mp3').html('');				
			$('#camera').html('');
			$('#canvasWrapper').hide();
			$('#canvasWrapper').css('margin-top','0');			
		},
		dialogClass: 'camera_dialog'
	});	
	
	$( "#qrcode-box" ).dialog({
		autoOpen: false,
		modal: true,
		width: 400,
		heigth: 200,
		resizable: false,
		buttons: {
			Ok: function() {
				$( this ).dialog( "close" );
			}
		}
	});
	
		$( "#login-facebook" ).dialog({
		autoOpen: false,
		modal: true,
		width: 400,
		heigth: 200,
		resizable: false,
		buttons: {
			Cancel: function() {
				$( this ).dialog( "close" );
			}
		}
	});

	$( "#promote-form" ).dialog({
		autoOpen: false,
		modal: true,
		width: 435,
		heigth: 400,
		resizable: false,
		buttons: {
			Ok: function() {
				$( this ).dialog( "close" );
			}
		}
	});
		
	function updateTips( t ) {
		tips.text( t ).addClass( "ui-state-highlight" );
		setTimeout(function() {
			tips.removeClass( "ui-state-highlight", 2000 );
		}, 500 );
	}

	function checkLength( o, n, min, max ) {
		if ( o.val().length > max || o.val().length < min ) {
			o.addClass( "ui-state-error" );
			updateTips( $("#t_msg1").val() +" ("+n+ ") "+$("#t_msg2").val()+" " +
				min + " "+$("#t_msg3").val()+"  (" + max + " max)." );
			return false;
		} else {
			return true;
		}
	}

	function checkRegexp( o, regexp, n ) {
		if ( !( regexp.test( o.val() ) ) ) {
			o.addClass( "ui-state-error" );
			updateTips( n );
			return false;
		} else {
			return true;
		}
	}

	function saveName() {
		var displayNameText = $("#displayNameText").val();		
		if(oldItem['name'] != displayNameText) {
			oldItem['name'] = displayNameText;
			postData = "saveForm=1";
			if(displayNameText!=undefined) {
				postData += "&displayName="+displayNameText;
				saveItem(postData,'SaveName');
			}
		}
	}
	
	function savePosition() {
		var positionText = $("#positionText").val();
		if(oldItem['position'] != positionText) {
			oldItem['position'] = positionText;
			postData = "saveForm=1";
			if(positionText!=undefined) {
				postData += "&position="+positionText;
				saveItem(postData,'SavePosition');			
			}
		}
	}
	
	function savePhone() {
		var phoneText = $("#phoneText").val();
		if(oldItem['phone'] != phoneText) {
			oldItem['phone'] = phoneText;
			postData = "saveForm=1";
			if(phoneText!=undefined) {
				postData += "&phone="+phoneText;
				saveItem(postData,'SavePhone');			
			}
		}
	}	

	function saveFax() {
		var faxText = $("#faxText").val();
		if(oldItem['fax'] != faxText) {
			oldItem['fax'] = faxText;
			postData = "saveForm=1";
			if(faxText!=undefined) {
				postData += "&fax="+faxText;
				saveItem(postData,'SaveFax');			
			}
		}
	}
	

	function saveForm(autoSave) {
	//	if(positionText==undefined)
	//		return;
		var about = $("#about").html();
		var name = $("#name").val();
		var newText = $("#wysiwyg").val();
		var newAddress = $("#wysiwyg_address").val();
		var displayNameText = $("#displayNameText").val();
		var positionText = $("#positionText").val();
		var phoneText = $("#phoneText").val();
		var faxText = $("#faxText").val();
		var commonBefore = '<div id="scrollBar1" class="scrollbarWrapper"><div class="scrollbar"><div class="track"><div class="thumb"><div class="end"></div></div></div></div><div class="viewport"><div class="overview">';		
		var addressBefore = '<div id="addressContent">'+commonBefore;
		var phoneTmpText = '<div id="phone">'+phoneText+'</div>';
		var faxTmpText = '<div id="fax">'+faxText+'</div>';
		var phoneFaxText = phoneTmpText+faxTmpText;

		if (!autoSave)
		{
			$("#address").html('<h4>'+$("#t_address").val()+'</h4>'+addressBefore+newAddress+'</div></div></div></div>'+phoneFaxText);
			addressContentScroll = $('#addressContent').tinyscrollbar();

			$("#about").html('<h4>'+$("#t_about").val()+'</h4>'+'<div id="aboutContent">'+commonBefore+newText+'</div></div></div></div>');
			aboutContentScroll = $('#aboutContent').tinyscrollbar();
			$("#displayName").html('<h1>'+displayNameText+'</h1>');			
			$("#position").html('<h2>'+positionText+'</h2>');			
		}

		$("#aboutText").val(newText);
		$("#addressText").val(newAddress);
		//$("#phone").html(phoneText);
		//$("#fax").html(faxText);
		$("#addNewIcon").remove();
		startDockMenu();
		
		
		/* save */
		$('#status').fadeIn('slow');
		$("#status").html('<img src="http://beename.com/images/loader.gif" align="absmiddle">'+$("#t_saving").val()+'...');
		postData = "saveForm=1";
		if(photoName!=undefined)
		postData += "&photoName="+photoName;
		if(newText!=undefined)
		postData += "&about="+newText;
		if(newAddress!=undefined)
		postData += "&address="+newAddress;
		if(displayNameText!=undefined) {
		postData += "&displayName="+displayNameText;
		}
		if(positionText!=undefined) {
		postData += "&position="+positionText;
		}
		if(phoneText!=undefined)
		postData += "&phone="+phoneText;
		if(faxText!=undefined)
		postData += "&fax="+faxText;
		if(isPhotoShown!=undefined)
		postData += "&showPhoto="+isPhotoShown;
		$.ajax({
	    	type: "POST",  
	    	url: "//beename.com/profile/SaveProfile",
	    	data: postData,
	    	
			success: function(server_response)
	    	{
				
	    		//$("#status").ajaxComplete(function(event, request)
	    	//	{
					if(photoName)
					$("#photo").html('<img width="100px" alt="'+name+'" title="'+name+'" src="http://beename.com/images/avatar/'+server_response+'_'+photoName+'?'+Math.floor(Math.random()*1000001)+'" />');
					if (!autoSave)
						$("#photo_up").html('');

	    	//	});
	
				if(server_response != '0')
					$('#growl').growlAlert('show', { content: trans['profile_saved'], title:$("#t_saved").val(), position:'top-right', delayTime: 4000 });
				else
					$('#growl').growlAlert('show', { 	content: trans['profile_not_saved'], title: $("#t_error").val(), position:'top-right', delayTime: 4000 });
				
				$('#status').fadeOut('slow');
					
	    	}
				
	    });
	}
	
	function fade_out() {
	  	$('#status').fadeOut('slow');
	}
    function createUploader(){
    	if(!isIE)
    		uploadPhotoText = trans['drop_photo'];
    	else
    		uploadPhotoText = trans['upload_photo'];
    		         
        var uploader = new qq.FileUploader({
            element: document.getElementById('photo_up'),
            action: '//beename.com/profile/uploadPhoto',
			template: '<div class="qq-uploader">' + 
                '<div class="qq-upload-drop-area"><div>'+trans['drop_files']+'</div></div>' +
                '<div class="qq-upload-button"><div>'+uploadPhotoText+'</div></div>' +
                '<ul class="qq-upload-list"></ul>' + 
             '</div>',
            allowedExtensions:  Array("jpg","jpeg","png","bmp"),
            sizeLimit: 3145728,
			onSubmit: function(id, fileName){
			createWallpaperUploader();					
			progressBar.progressbar("value",0);					
			$("#progressbar").show();
			},
			onProgress: function(id, fileName, loaded, total) {
			var percent = Math.round(loaded / total * 100);
			progressBar.progressbar("value",percent);
			},                        
			onComplete: function(id, fileName, result){
				$("#progressbar").hide();				
				if(!result.success)
					return;
				var userID = $('#id').val();
				photoIdName = userID + '_' + fileName;
				photoName = fileName;
				var dialog = $( "#crop-image" ).dialog( "open" );				
				$("#crop_photo").html('<img id="photoEdit" src="http://beename.com/images/avatar/'+userID+'_'+fileName+'?'+Math.random()*1000000+'"/>');					
				$('#photoEdit').attr('style','min-width: 130px; min-height: 162px; max-width: 500px; max-height: 430px;');	
				$("#thumb_image").attr("src",'http://beename.com/images/avatar/'+userID+'_'+fileName);
				var curImg = $('img#photoEdit');			
				crop = curImg.imgAreaSelect({ x1: 0, y1: 0, x2: 130, y2: 162, handles: true, zIndex: 2000, aspectRatio: "130:162", minWidth: 130, minHeight: 162, fadeSpeed: 200, onSelectChange: preview, parent: $('.crop_image_dialog'), onInit: function (img, selection) {
					curSelection=new Object();
					curSelection.width = 130;
					curSelection.height = 162;
					curSelection.x1 = 0;
					curSelection.x2 = 130;
					curSelection.y1 = 0;					
					curSelection.y2 = 162;
					var newImg = document.getElementById('photoEdit');
					preview(newImg,curSelection);
					}});
			}
        });           
    }
	
	$('#cameraOpen').click(function() {
		canvas = document.getElementById("canvas");				
		camera_dialog = $( "#cameraParent" ).dialog( "open" );
		if (canvas.getContext) {
				ctx = document.getElementById("canvas").getContext("2d");
				ctx.clearRect(0, 0, 320, 240);

				var img = new Image();
				img.src = "bee_power.jpg";
				img.onload = function() {
					ctx.drawImage(img, 0, 0);
				}
				try {
				image = ctx.getImageData(0, 0, 320, 240);
				} catch(e){}
			}
					
			$('#camera').focus();
			camera = $("#camera").webcam({
	        width: 480,
	        height: 360,
	        mode: "callback",
	        swffile: "//beename.com/lib/profile/webcam/jscam_canvas_only.swf",
	        onTick: function(remain) {
			 timeRemain = remain+1;
			        jQuery("#countDown").html(''+timeRemain);
			},
	        onSave: function(data) {
						var col = data.split(";");
						var img = image;
						
						if (false == filter_on) {

							for(var i = 0; i < 320; i++) {
								var tmp = parseInt(col[i]);
								img.data[pos + 0] = (tmp >> 16) & 0xff;
								img.data[pos + 1] = (tmp >> 8) & 0xff;
								img.data[pos + 2] = tmp & 0xff;
								img.data[pos + 3] = 0xff;
								pos+= 4;
							}

						} else {

							var id = filter_id;
							var r,g,b;
							var r1 = Math.floor(Math.random() * 255);
							var r2 = Math.floor(Math.random() * 255);
							var r3 = Math.floor(Math.random() * 255);

							for(var i = 0; i < 320; i++) {
								var tmp = parseInt(col[i]);
								/* Copied some xcolor methods here to be faster than calling all methods inside of xcolor and to not serve complete library with every req */
								if (id == 0) {
									r = (tmp >> 16) & 0xff;
									g = 0xff;
									b = 0xff;
								} else if (id == 1) {
									r = 0xff;
									g = (tmp >> 8) & 0xff;
									b = 0xff;
								} else if (id == 2) {
									r = 0xff;
									g = 0xff;
									b = tmp & 0xff;
								} else if (id == 3) {
									r = 0xff ^ ((tmp >> 16) & 0xff);
									g = 0xff ^ ((tmp >> 8) & 0xff);
									b = 0xff ^ (tmp & 0xff);
								} else if (id == 4) {

									r = (tmp >> 16) & 0xff;
									g = (tmp >> 8) & 0xff;
									b = tmp & 0xff;
									var v = Math.min(Math.floor(.35 + 13 * (r + g + b) / 60), 255);
									r = v;
									g = v;
									b = v;
								} else if (id == 5) {
									r = (tmp >> 16) & 0xff;
									g = (tmp >> 8) & 0xff;
									b = tmp & 0xff;
									if ((r+= 32) < 0) r = 0;
									if ((g+= 32) < 0) g = 0;
									if ((b+= 32) < 0) b = 0;
								} else if (id == 6) {
									r = (tmp >> 16) & 0xff;
									g = (tmp >> 8) & 0xff;
									b = tmp & 0xff;
									if ((r-= 32) < 0) r = 0;
									if ((g-= 32) < 0) g = 0;
									if ((b-= 32) < 0) b = 0;
								} else if (id == 7) {
									r = (tmp >> 16) & 0xff;
									g = (tmp >> 8) & 0xff;
									b = tmp & 0xff;
									r = Math.floor(r / 255 * r1);
									g = Math.floor(g / 255 * r2);
									b = Math.floor(b / 255 * r3);
								}

								img.data[pos + 0] = r;
								img.data[pos + 1] = g;
								img.data[pos + 2] = b;
								img.data[pos + 3] = 0xff;
								pos+= 4;
							}
						}

						if (pos >= 0x4B000) {
							ctx.putImageData(img, 0, 0);
							pos = 0;
						}
						$('#canvasWrapper').css('margin-top','-361px');
						$('#canvasWrapper').show();

		
	},
	        onCapture: function() {
				$(".mp3").jmp3({"fileName": 'sound.mp3'	});	
				webcam.save();
				$('a#takeNew').show();
				jQuery("#countDown").html('');
				jQuery("#flashEffect").css("display", "block");
				jQuery("#flashEffect").fadeOut(100, function () {
					jQuery("#flashEffect").css("opacity", 1);
				});

		},
	        debug: function() {},
	        onLoad: function() {
				document.getElementById('XwebcamXobjectX').focus();
				//$("#camera").show();
			}
		});
	});

	$('#removePhoto').click(		
		function() {
				$.ajax({
			    	type: "POST",  
			    	url: "//beename.com/profile/DeleteImage",
			    	data: 'removePhoto=1',
			    	success: function(server_response)
			    	{
			    		if(server_response) {
							photoName = undefined;
							$('#photo').html('');
							$('#removePhoto').hide();
						}
			    	} 
			    });		
		});

	$('#switchPhoto').click(
		function() {
			var marginLeft = -160;
			var marginRight = 400;
			
			if(isPhotoShown) {
				hidePhoto();
			}
			else {
				showPhoto();		
			}
	}			
			 			
	);
	
	$('#cameraBtn').click(
		function() {
			$('#canvasWrapper').hide();
			$('#canvasWrapper').css('margin-top','0');			
			try {
			webcam.capture(2);
			}
			catch(e) {
				alert(trans['photo_error2']);
				 $( "#cameraParent" ).dialog( "close" );				
				 $( "#status" ).fadeOut( 'slow' );				

			}
		}
	);
	
	$('a#takeNew').click(
		function() {
			$('#canvasWrapper').hide();
			$('#canvasWrapper').css('margin-top','0');				
			$('a#takeNew').hide();
		}
	);
	
	$('#beeWrapper').click(
		function(e) {
                e.preventDefault();
				$.ajax({
			    	type: "POST",  
			    	url: "//beename.com/profile/updateCardHolder",
			    	data: 'userCard='+$('#id').val(),
			    	success: function(server_response)
			    	{
			    		if(server_response=='1') 
						{
							//$('#beeWrapper').html("<a href=\"#\" id=\"beeHoverIcon\" class=\"bubble\">Beename</a>");							
							//$('#beeHoverIcon').SetBubblePopupInnerHtml('Remove from favorites');
							$('#beeIcon').addClass('noIcon');
							$('#beeHoverIcon').removeClass('noIcon');	
							$('#beeIcon').RemoveBubblePopup();
							createBubbleHoverIcon();	
				
							$('#growl').growlAlert('show', { content: trans['add_card_holder2'], title:$("#t_saved").val(), position:'top-right', delayTime: 4000 });
						}
						else if (server_response=='2')
						{
							//$('#beeWrapper').html("<a href=\"#\" id=\"beeIcon\" class=\"bubble\">Beename</a>");							
							//$('#beeIcon').SetBubblePopupInnerHtml('Add to favorites');
							$('#beeHoverIcon').addClass('noIcon');
							$('#beeIcon').removeClass('noIcon');
							$('#beeHoverIcon').RemoveBubblePopup();
							createBubbleIcon();							
							$('#growl').growlAlert('show', { content: trans['del_card_holder2'], title:$("#t_saved").val(), position:'top-right', delayTime: 4000 });							
						}
			    	} 
			    });		
		});
//	alert($('.serviceType').size()+'');	
	xCounter = $('#x_counter').val();
	$('a#add_new_website').click(
		function() {
			if (xCounter<7)
			{
				$('.other_websites').append('<div class="otherWebsite" id="custom_'+xCounter+'"><a href="#" class="delCustomService" onClick="hideWebsiteForm('+xCounter+')">x</a><label>'+trans['desc']+': </label><input type="text" maxlength="40" id="desc['+xCounter+']" name="desc['+xCounter+']"/><label>'+trans['link']+': </label><input type="text" id="link_'+xCounter+'" name="link['+xCounter+']"/><label>'+trans['icon']+': </label><select id="type_'+xCounter+'" name="type['+xCounter+']"><option value="1001" title="http://beename.com/lib/profile/css-dock-menu/images/icons/other.png">'+trans['other']+'</option><option value="1002" title="http://beename.com/lib/profile/css-dock-menu/images/icons/business.png">'+trans['business']+'</option><option value="1003" title="http://beename.com/lib/profile/css-dock-menu/images/icons/private.png">'+trans['private']+'</option><option value="1004" title="http://beename.com/lib/profile/css-dock-menu/images/icons/research.png">'+trans['research']+'</option><option value="1005" title="http://beename.com/lib/profile/css-dock-menu/images/icons/blog.png">'+trans['blog']+'</option><option value="1006" title="http://beename.com/lib/profile/css-dock-menu/images/icons/rss.png">'+trans['rss']+'</option></select></div>');
			$('#type_'+xCounter).msDropDown({'row-height' : '50px'});
			}
			xCounter++;
		}
	);	
});

	function saveItem(postData, actionName) {
		$('#status').fadeIn('slow');
		$("#status").html('<img src="http://beename.com/images/loader.gif" align="absmiddle">'+$("#t_saving").val()+'...');

		$.ajax({
		    	type: "POST",  
		    	url: "//beename.com/profile/"+actionName,
		    	data: postData,
		    	
				success: function(server_response)
		    	{
							
					if(server_response != '0') {
						$('#growl').growlAlert('show', { content: trans['profile_saved'], title:$("#t_saved").val(), position:'top-right', delayTime: 4000 });
					}
					else
						$('#growl').growlAlert('show', { 	content: trans['profile_not_saved'], title: $("#t_error").val(), position:'top-right', delayTime: 4000 });
					
					$('#status').fadeOut('slow');
						
		    	}
					
		    });
	
	}
	function saveAddressAbout() {
		postData = "saveForm=1";
		var newAddress = $("#wysiwyg_address").val();
		var newText = $("#wysiwyg").val();		
		if(newText!=undefined)
			postData += "&about="+newText;
		if(newAddress!=undefined)
			postData += "&address="+newAddress;
		saveItem(postData,'SaveAddressAbout');			

	}		
	
function hideWebsiteForm(x)
{
   	numrow = "#custom_"+x;
    link = "#link_"+x;
	$(link).val("");
	$(numrow).fadeOut('slow',function() {$(this).remove();});
	xCounter--;
}

		function saveShowPhoto(isShown) {
			postData = "saveForm=1";
			postData += "&showPhoto="+isShown;
			saveItem(postData,'SaveShowPhoto');			
		}
		
function hidePhoto() {
	
	var marginLeft = -160;
	var marginRight = 400;
	
	$('#photo').animate(
		{'margin-left': marginLeft}, 500);
	
	$('#card_content, #scrollBar1').animate(
		{'width': marginRight}, 500);
	
	
	$('.viewport').animate(
		{'width': marginRight-15}, 500, function() {
			addressContentScroll.tinyscrollbar_update();
			aboutContentScroll.tinyscrollbar_update();					
		});
		
	$('#switchPhoto').addClass('switchShow');
	saveShowPhoto('0');
	isPhotoShown = 0;	
}

function showPhoto() {
	
	$('#photo').animate(
		{'margin-left': 0}, 500);

	$('#card_content, #scrollBar1').animate(
		{'width': 240}, 500);

	$('.viewport').animate(
		{'width': 225}, 500, function() {
			addressContentScroll.tinyscrollbar_update();
			aboutContentScroll.tinyscrollbar_update();					
		});
	
	$('#switchPhoto').removeClass('switchShow');			
	saveShowPhoto('1');
	isPhotoShown = 1;
}

function displaySocials() {
	$('.serviceType').msDropDown({'row-height' : '50px'});
	$( "#icon-select-form" ).dialog( "open" );
	return false;
}

function displayMessageForm() {
	$( "#dialog-form" ).dialog( "open" );
}

function displayShareWithFriendsForm() {
	$( "#share-dialog-form" ).dialog( "open" );
}

function displayQRCodeBox() {
	$( "#qrcode-box" ).dialog( "open" );
}

function displayPromoteBox() {
	$( "#promote-form" ).dialog( "open" );
	return false;
}

function startDockMenu() {
	$('#dock2').Fisheye(
		{
			maxWidth: 60,
			items: 'li',
			itemsText: 'span',
			container: '.dock-container2',
			itemWidth: 70,
			proximity: 120,
			alignment : 'left',
			valign: 'bottom',
			halign : 'center'
		}
	);
}

function loadjscssfile(filename, filetype, id){
 if (filetype=="js"){ //if filename is a external JavaScript file
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
  fileref.setAttribute("id", id)
 }
 else if (filetype=="css"){ //if filename is an external CSS file
  var fileref=document.createElement("link")
  fileref.setAttribute("rel", "stylesheet")
  fileref.setAttribute("type", "text/css")
  fileref.setAttribute("href", filename)
  fileref.setAttribute("id", id)
 }
 if (typeof fileref!="undefined")
  document.getElementsByTagName("head")[0].appendChild(fileref)
}

function centerCard() {
	var windowHeight = $(window).height();
	newTop = ((windowHeight - 230)/2)-200;
	if(newTop<0)
		newTop = 0;
	$('#cardWrapper').animate({'top': newTop},500);
}

function createBubbleIcon () {
			//Bubble popup
					//create a bubble popup for each DOM element with class attribute as "text", "button" or "link" and LI, P, IMG elements.
					$('#beeIcon').CreateBubblePopup({
												position : 'bottom',
												align	 : 'left',
												tail: {align: 'left'},
												innerHtmlStyle: {
																	color:'#FFFFFF', 
																	'text-align':'center'
																},
												themeName: 	'all-black',
												themePath: 	'//beename.com/images/jquerybubblepopup-theme',
												innerHtml: trans['add_card_holder']
					});
}

function createBubbleHoverIcon () {
			//Bubble popup
					//create a bubble popup for each DOM element with class attribute as "text", "button" or "link" and LI, P, IMG elements.
					$('#beeHoverIcon').CreateBubblePopup({
												position : 'bottom',
												align	 : 'left',
												tail: {align: 'left'},												
												innerHtmlStyle: {
																	color:'#FFFFFF', 
																	'text-align':'center'
																},
												themeName: 	'all-black',
												themePath: 	'//beename.com/images/jquerybubblepopup-theme',
												innerHtml: trans['del_card_holder']
					});
}

    function createWallpaperUploader(){    
		//$preloader.fadeIn("fast"); //show preloader        
        var uploader = new qq.FileUploader({
            element: document.getElementById('wallpaper_up'),
            action: '//beename.com/profile/uploadWallpaper',
			template: '<div class="qq-uploader">' + 
		                '<div class="qq-upload-drop-area"><div>'+trans["drop_files"]+'</div></div>' +
		                '<div class="qq-upload-button"><div>'+trans['upload_wallpaper']+'</div></div>' +
		                '<ul class="qq-upload-list"></ul>' + 
		             '</div>',
            allowedExtensions:  Array("jpg","jpeg","png","bmp"),
            sizeLimit: 5242880,            		             
			onSubmit: function(id, fileName){		
			progressBar.progressbar("value",0);									
			$("#progressbar").show();
			},
			onProgress: function(id, fileName, loaded, total) {
			var percent = Math.round(loaded / total * 100);
			progressBar.progressbar("value",percent);
			},
			onComplete: function(id, fileName, result){
				$("#progressbar").hide();
				if(!result.success) {
					return;
				}
				
				var last = fileName.lastIndexOf('.');
				var extension = fileName.substr(last);
				
				var wallpaperName = '//beename.com/images/wallpapers/user/'+$("#id").val() + '_bee_wallpaper'+extension+'?'+(Math.random()*1000001);
				
					$bgimg.css("display","none");
					$preloader.fadeIn("fast"); //show preloader
					//style clicked thumbnail
					$outer_container_a.each(function() {
			    		$(this).children(".selected").css("display","none");
			  		});
					$(this).children(".selected").css("display","block");
					//get and store next image and selected thumb 
				
				$bgimg.attr("src", "").attr("src", wallpaperName);				
			}
        });           
    }
