var image_object;
var save_cur_image;
var im_crop_area;
var try_image_url;
var alert_can_not_do_while_in_process = 'Sorry can not do that while in process.';
var image_editor_path = '/js/s101_admin/image_editing/';
var default_select_img = image_editor_path+'img/select_image.png';
var sn_script_path = '/js/s101_admin/social_networks/';


function image_editor_load(img_id, show_hide_switch, embed_area_width, embed_area_height, load_to_div_id, db_slug_name, image_size, custom_function_on_close, collection_id) {

    var cur_image_src = '';


//______________________________________
//START opening modes
    if (show_hide_switch == 'select')
    {
        cur_image_src = default_select_img;
    }
    else if (show_hide_switch == 'input')
    {
        var cur_image_src_tmp = document.getElementById(img_id).value;
        cur_image_src = cur_image_src_tmp.length >= 5 ? cur_image_src_tmp : default_select_img;
    }
    else
    {
        cur_image_src = document.getElementById(img_id).src.split('?q=')[0].replace('_thumb', '_md');
    }
//______________________________________
//END opening modes


    if (cur_image_src.indexOf('/') >= 1)
    {
        var cur_image_filename = cur_image_src.split('/').pop();
    }
    else
    {
        var cur_image_filename = cur_image_src;
    }


		if (image_size == 'full') {

			cur_image_filename = cur_image_filename.replace('_md.jpg','.jpg');
			cur_image_filename = cur_image_filename.replace('_md.png','.png');

			cur_image_src = cur_image_src.replace('_md.jpg','.jpg');
			cur_image_src = cur_image_src.replace('_md.png','.png');

		} else {

			cur_image_filename = cur_image_filename.replace('_md.jpg',image_size + '.jpg');
			cur_image_filename = cur_image_filename.replace('_md.png',image_size + '.png');

			cur_image_src = cur_image_src.replace('_md.jpg',image_size + '.jpg');
			cur_image_src = cur_image_src.replace('_md.png',image_size + '.png');

		}

    if (show_hide_switch == 'show' || show_hide_switch == 'select' || show_hide_switch == 'input')
    {
    	$('#img_editor_pre_wrap').remove();

    	if (load_to_div_id.length == 0)
    	{
        	$('<div id="img_editor_pre_wrap"></div>').insertAfter($('#'+img_id));
        	var load_in_to_id_inp_val = '_self_';
    	}
    	else
    	{
    		$('#'+load_to_div_id).html('<div id="img_editor_pre_wrap"></div>');
    		var load_in_to_id_inp_val = load_to_div_id;
    	}

    	$('#img_editor_pre_wrap').load(image_editor_path+'tpl.php #image_editor', function() {

            image_editor_load_init(show_hide_switch, cur_image_src, cur_image_filename, embed_area_width, embed_area_height);

            if (document.getElementById('editor_object_id').value=='')
			{
				if (load_to_div_id == 'im_editor_load_to_div_centered' && show_hide_switch != 'select')
				{
				    document.getElementById('edit_or_replace').style.display='block';
				}
			}
            document.getElementById('init_image_path').value = cur_image_src;
            document.getElementById('load_in_to_id_inp').value = load_in_to_id_inp_val;

            if (collection_id != 'save_final_processing' && collection_id.length >= 1)
            {
                document.getElementById('img_editor_collection_id').value = collection_id;
            }

            document.getElementById('img_id_inp').value=img_id;
            document.getElementById('action_switch').value=show_hide_switch;
            document.getElementById('db_slug_name').value=db_slug_name;
            document.getElementById('embed_area_width').value=embed_area_width;
			document.getElementById('embed_area_height').value=embed_area_height;
			document.getElementById('embed_area_size').innerHTML='('+embed_area_width+'x'+embed_area_height+')';
			document.getElementById('embed_area_alert').value='';
			document.getElementById('custom_function_on_close').value=custom_function_on_close;

			if (embed_area_height.length==0)
	        {
	            document.getElementById('embed_info_row_key').style.display='none';
	            document.getElementById('embed_info_row_val').style.display='none';
	            document.getElementById('size_to_embed').style.display='none';

	            if (embed_area_width.length==0)
	            {
	                document.getElementById('load_new_im').style.display='none';
	            }
	        }
	        else
	        {
	            document.getElementById('embed_info_dimention_w').innerHTML=embed_area_width;
	            document.getElementById('embed_info_dimention_h').innerHTML=embed_area_height;
	            document.getElementById('embed_info_row_key').style.display='table-cell';
	            document.getElementById('embed_info_row_val').style.display='table-cell';
	            document.getElementById('size_to_embed').style.display='block';
	            document.getElementById('load_new_im').style.display='block';
	        }
	    });
    }
	else
	{
        image_editor_load_init(show_hide_switch, cur_image_src, cur_image_filename, embed_area_width, embed_area_height);
	}
}


function image_editor_load_init(show_hide_switch, cur_image_src, cur_image_filename, embed_area_width, embed_area_height) {

    $('.img_editor_control_switch').removeClass('img_editor_but_selected');
    $('.img_editor_control_section').slideUp(300);

    document.getElementById('im_edited_wrap_img').innerHTML='<img src="'+cur_image_src+'?q='+Math.random()+'" alt="" id="im_edited" />';

    document.getElementById('orig_image_path').value=cur_image_src;
    document.getElementById('image_info_filename').value=cur_image_filename;
    document.getElementById('embed_area_alert').value='';
    document.getElementById('image_file_info_alerts').style.display='none';

    if (show_hide_switch == 'input')
    {
        if (cur_image_src == default_select_img)
        {
            image_editor_select_mode();
            return;
        }
        else
        {
            img_process('load_img_new', '', '', '', '');
            show_hide_switch = 'show';
        }
    }
    else if (show_hide_switch == 'select')
    {
        image_editor_select_mode();
        return;
    }
    else
    {
        img_process('load_img_new', '', '', '', '');
    }

    if (show_hide_switch == 'show')
	{
		$('#image_editor').fadeIn(300);
	}
}


function image_editor_select_mode() {

    document.getElementById('im_edited').style.display='none';

    $('#image_editor').fadeIn(300, function() {

        load_new_image('show', '');
        $('#im_edited').delay(300).fadeIn(600);
    });
}


function load_new_image(action, collection_id) {


	if (document.getElementById('image_editor_process').value >= '1')
	{
		blink_image_file_info_alerts(alert_can_not_do_while_in_process);
		return;
	}

	$('#img_editor_history_nav').fadeOut(300);
	cleanup_crop();

	$('.img_editor_control_switch').removeClass('img_editor_but_selected');
    $('.img_editor_control_section').slideUp(300);
    $('#more_effects').fadeOut(300);

    if (action == 'hide')
    {
    	var cur_full_im_src = document.getElementById('im_edited').src.split('?q=')[0];
    	var cur_file_name = cur_full_im_src.split('/').pop();

    	if (cur_file_name == 'select_image.png')
	    {
	        $('#im_edited').fadeOut(400, function() {

	            $('#im_edited').fadeIn(90);
	        });
	        return;
	    }

	    document.getElementById('load_new_image_edited').innerHTML='';

    	$('#load_external_nav').slideUp(600, function() {
    		document.getElementById('external_img_url').value='';
    		document.getElementById('image_url_row_message').innerHTML='Input image URL to load from WEB';
    		document.getElementById('im_editor_upload_zone').innerHTML='';
    	});
    }

    if (action == 'reload_collection')
    {

    	$('#external_images_batch').fadeOut(300, function() {

    		$('#external_images').append('<img src="'+image_editor_path+'img/loading.gif" alt="" id="images_batch_loading" />');
    		$('#load_new_image_edited').load('/?page=admin_img_editor_collections&collection_id='+encodeURI(collection_id)+' #external_images', function() {
    			$('#images_batch_loading').remove();
    		});
    	});
    	return;
    }


    if ($('#load_new_image_edited').is(':hidden'))
    {


    	$('#load_external_nav').slideDown(600, function(){

    		var user_name = document.getElementById('user_name').value;
    		var uploader = new imm.FileUploader({
            	element: document.getElementById('im_editor_upload_zone'),
            	action: image_editor_path+'upload.php',
            	allowedExtensions: ['jpg', 'png'],
            	params: {
                	user_dir: 'tmp/'+user_name,
                	upl_dir: 'tmp/'+user_name+'/uploads',
                	rand: Math.random()
            	},
            	onCancel: function(id, fileName) {
            		document.getElementById('im_upload_button').style.display='block';
            	},
            	onSubmit: function(id, fileName) {

            		document.getElementById('im_upload_button').style.display='none';
            	},
            	onComplete: function(id, fileName, response) {

                    document.getElementById('im_upload_button').style.display='block';
                    document.getElementById('external_img_url').value = 'uploads/'+response.new_fileName;
                    document.getElementById('im_editor_upload_zone_list').innerHTML='';
                    external_url_try();
            	}
            });
        });
    }

    $('#load_new_image_edited').animate({width: action}, 600, function() {


    	if (action == 'show')
    	{

    		collection_id = document.getElementById('img_editor_collection_id').value;

    		$('#load_new_image_edited').html('<img src="'+image_editor_path+'img/loading.gif" alt="" id="images_batch_loading" />');
    		$('#load_new_image_edited').load('/?page=admin_img_editor_collections&collection_id='+encodeURI(collection_id)+' #external_images');

    		$('#load_new_im').attr('onclick', 'load_new_image(\'hide\', \'\');');
    		$('#load_new_im').attr('class', 'img_editor_but_history img_editor_but_selected');
    		$('#load_new_im').attr('value', 'Ok');
    	}
    	else
    	{

    		var im_path = document.getElementById('im_edited').src;

    		$('#load_new_im').attr('onclick', 'load_new_image(\'show\', \'\');');
    		$('#load_new_im').attr('class', 'img_editor_but_history');
    		$('#load_new_im').attr('value', 'Replace Image');

    		if (im_path.indexOf('nopic.jpg') >= 1)
	        {
		        document.getElementById('img_editor_controls').style.display='none';
		        document.getElementById('editing_impossible').style.display='block';
		        document.getElementById('image_file_info').style.display='none';
		        document.getElementById('image_file_info_messages_table').style.display='none';
		        return;
	        }
	        else
	        {
	            document.getElementById('img_editor_controls').style.display='block';
		        document.getElementById('editing_impossible').style.display='none';
		        document.getElementById('image_file_info').style.display='block';
		        document.getElementById('image_file_info_messages_table').style.display='table';
    		    $('#img_editor_history_nav').fadeIn(300);
    	    }
    	}
    });
}


function img_process(action, a, b, c, d) {

	//don't start a new process while previous is running
	if (document.getElementById('image_editor_process').value >= '1')
	{
		if (action == 'process_stop')
		{
			if (image_object.readystate != 4)
			{
				image_object.abort();
				stop_current_process();
			}
			return;
		}
		else if (action == 'history')
		{
			if (image_object.readystate != 4)
			{
				image_object.abort();
				stop_current_process();
			}
			else
			{
				return;
			}
		}
		else
		{
			blink_image_file_info_alerts(alert_can_not_do_while_in_process);
			return;
		}
	}

	var im_path = document.getElementById('im_edited').src.split('?q=')[0];
	var im_path_orig = document.getElementById('orig_image_path').value;
	var object_id = document.getElementById('img_id_inp').value;
	var user_name = document.getElementById('user_name').value;
	var cur_history = document.getElementById('version_history').value;
	var cur_max_history = document.getElementById('cur_max_history').value;

	var user_set_width = document.getElementById('im_width').value;
	var user_set_height = document.getElementById('im_height').value;
	var embed_area_width = document.getElementById('embed_area_width').value;
    var embed_area_height = document.getElementById('embed_area_height').value;
    document.getElementById('image_file_info_alerts').style.display='none';


//"editing impossible" part (used if user loads a corrupt image)
	if (im_path.indexOf('nopic.jpg') >= 1)
	{
		document.getElementById('img_editor_controls').style.display='none';
		document.getElementById('editing_impossible').style.display='block';
		document.getElementById('img_editor_history_nav').style.display='none';
		document.getElementById('image_file_info').style.display='none';
		document.getElementById('image_file_info_messages_table').style.display='none';
		return;
	}
	else
	{
	    document.getElementById('img_editor_controls').style.display='block';
		document.getElementById('editing_impossible').style.display='none';
		document.getElementById('image_file_info').style.display='block';
		document.getElementById('image_file_info_messages_table').style.display='table';
	}


	//check if image sizes are workable and realistic
	if (action == 'scaleImage')
	{
	    if (img_size_check(user_set_width, user_set_height, embed_area_width, embed_area_height) != true)
	    {
	    	return;
	    }
	}

    image_object = $.ajax({
		type: 'POST',
		url: image_editor_path+'process.php',
		data:
		{
			user_name: user_name,
			object_id: object_id,
			im_path: im_path,
			im_path_orig: im_path_orig,
			action: action,
			cur_history: cur_history,
			cur_max_history: cur_max_history,
			a: a,
			b: b,
			c: c,
			d: d
		},
		beforeSend: function(image_object)
		{
    		if (action != 'cropImage')
    		{
    			cleanup_crop();
    		}

    		im_editor_process_time_start();
    		document.getElementById('image_file_info_messages').innerHTML='<img src="'+image_editor_path+'img/loading.gif" alt="" id="images_process_loading" /><div id="process_stop" onclick="img_process(\'process_stop\', \'\', \'\', \'\', \'\');">stop process</div>';
		},
  		success: function(content)
		{
			cleanup_crop();
			var image_info = jQuery.parseJSON(content);
			var new_im_url = image_info.im_path_orig;
			var new_history = image_info.history;
			var new_width = image_info.width;
			var new_height = image_info.height;
			var new_resolution = image_info.resolution;
			var new_file_size = image_info.file_size;
			var action_name = image_info.action_name;


			if (document.getElementById('image_file_info_alerts').innerHTML==alert_can_not_do_while_in_process)
			{
				document.getElementById('image_file_info_alerts').style.display='none';
			}

			//reality check...
			if (new_width == undefined)
			{
				document.getElementById('image_file_info_messages').innerHTML='<div class="fatal_error">Hmm...<br />Your last process did not complete.<br /><br /><small>Try reducing image size prior applying the filter.</small></div>';
				document.getElementById('image_editor_process').value='';
				return;
			}


			if (action == 'load_img_new' && document.getElementById('editor_object_id').value=='')
			{
				var object_date_year = image_info.object_date_year;
			    var object_date_month = image_info.object_date_month;
			    var object_date_day = image_info.object_date_day;

				document.getElementById('editor_object_id').value=image_info.editor_object_id;
				document.getElementById('im_title').value=image_info.description;
				document.getElementById('im_link').value=image_info.im_link;
				document.getElementById('im_tags').value=image_info.tags;
				document.getElementById('im_notes').innerHTML=image_info.display_text;


            	//set the date
            	select_option_value(document.im_edit_f.yearselect, object_date_year);
            	select_option_value(document.im_edit_f.monthselect, object_date_month);
				select_option_value(document.im_edit_f.dayselect, object_date_day);

				if (object_date_year.length != 0)
				{
				    month_days(object_date_day, object_date_month, object_date_year);
				}
			}

			if (Number(new_history) <= 0)
			{
				document.getElementById('version_history').value='0';

				if (action != 'load_img_new')
				{
					swap_images(im_path_orig+'?q='+Math.random(), im_path_orig);
				}

				document.getElementById('history_undo').removeAttribute('onclick');
				document.getElementById('history_undo').setAttribute('class', 'img_editor_but_undo_disabled');

				document.getElementById('history_revert').removeAttribute('onclick');
				document.getElementById('history_revert').setAttribute('class', 'img_editor_but_revert_disabled');
			}
			else
			{
				document.getElementById('version_history').value=new_history;

				if (action != 'load_img_new')
				{
				    swap_images(new_im_url+'?q='+Math.random(), im_path_orig);
				}

				document.getElementById('history_undo').setAttribute('class', 'img_editor_but_undo');
				document.getElementById('history_undo').setAttribute('onclick', 'img_process(\'history\', -1, \'\', \'\', \'\');');

				document.getElementById('history_revert').setAttribute('class', 'img_editor_but_revert');
				document.getElementById('history_revert').setAttribute('onclick', 'img_process_revert();');
			}


            //history_redo switch
	        if (Number(new_history) < Number(cur_max_history))
	        {
	            document.getElementById('history_redo').setAttribute('class', 'img_editor_but_redo');
				document.getElementById('history_redo').setAttribute('onclick', 'img_process(\'history\', 1, \'\', \'\', \'\');');
	        }
	        else
	        {
	            document.getElementById('history_redo').removeAttribute('onclick');
				document.getElementById('history_redo').setAttribute('class', 'img_editor_but_redo_disabled');
	        }


	        //cur_max_history switch
	        if (action == 'history')
	        {
	            if (Number(a) <= 0 && cur_max_history == '0')
		        {
			        document.getElementById('cur_max_history').value=cur_history;
			        document.getElementById('history_redo').setAttribute('class', 'img_editor_but_redo');
					document.getElementById('history_redo').setAttribute('onclick', 'img_process(\'history\', 1, \'\', \'\', \'\');');
		        }
	        }
	        else
	        {
		        document.getElementById('cur_max_history').value='0';
		        document.getElementById('history_redo').removeAttribute('onclick');
				document.getElementById('history_redo').setAttribute('class', 'img_editor_but_redo_disabled');
	        }


	        //set image info and properties
	        document.getElementById('image_info_dimention_w').innerHTML=new_width;
	        document.getElementById('image_info_dimention_h').innerHTML=new_height;
	        document.getElementById('cur_im_width').value=new_width;
	        document.getElementById('cur_im_height').value=new_height;
	        document.getElementById('image_info_resolution').innerHTML=new_resolution;
	        document.getElementById('image_info_size').innerHTML=new_file_size;
	        document.getElementById('image_file_info_messages').innerHTML=action_name;
	        document.getElementById('image_editor_process').value='';

            //double-check image size post processing
	        if (action != 'load_img_new' && document.getElementById('embed_area_alert').value.length==0)
	        {
	            if (img_size_check(new_width, new_height, embed_area_width, embed_area_height) != true)
	            {
	                document.getElementById('embed_area_alert').value='1';
	            }
	        }
		}
	});
}


function crop_init() {

	if (document.getElementById('image_editor_process').value >= '1')
	{
		blink_image_file_info_alerts(alert_can_not_do_while_in_process);
		return;
	}

	//get and set onscreen im_edited image sizes
	var img_edited_q = new Image();
	img_edited_q.src = document.getElementById('im_edited').src;
	var img_edited_q_height = img_edited_q.height;
	var img_edited_q_width = img_edited_q.width;
	var embed_area_width = document.getElementById('embed_area_width').value;
	var embed_area_height = document.getElementById('embed_area_height').value;

	var animate_to_q_x = Math.round(img_edited_q_width / 4 - 10);
	var animate_to_q_y = Math.round(img_edited_q_height / 4);
	var animate_to_q_x2 = Math.round(img_edited_q_width - animate_to_q_x);
	var animate_to_q_y2 = Math.round(img_edited_q_height - animate_to_q_y + 10);


	if (document.im_edit_f.im_ratio.checked==true)
    {
		var im_size_ratio_option = 'ratio';
	}
	else if (document.im_edit_f.im_size_to_area.checked==true)
	{
		var im_size_ratio_option = 'size';
		animate_to_q_x = 100;
		animate_to_q_y = 100;
		animate_to_q_x2 = embed_area_width;
		animate_to_q_y2 = embed_area_height;
	}

	if (document.im_edit_f.im_size_to_area.checked==false)
	{
		document.getElementById('im_width').value='';
		document.getElementById('im_height').value='';
	}

	$('#im_edited').Jcrop(
	{
		trueSize: [img_edited_q_width, img_edited_q_height],
		onChange: set_cur_pos,
        onSelect: set_cur_pos,
	},
		function()
		{
			im_crop_area = this;
			set_size_ratio(im_size_ratio_option);
			im_crop_area.animateTo([animate_to_q_x, animate_to_q_y, animate_to_q_x2, animate_to_q_y2]);
		}
	);

	document.getElementById('crop_but').setAttribute('onclick', 'apply_crop();');
	document.getElementById('crop_but').setAttribute('value', 'apply crop');
	$('#cancel_crop_but').fadeIn(300);
}


function set_size_ratio(size_ratio_option) {

    var embed_area_width=document.getElementById('embed_area_width').value;
	var embed_area_height=document.getElementById('embed_area_height').value;
	var keep_proportion_of_obj = embed_area_height.length >= 1 ? 'embed area' : 'image';

	//image/embed area crop ratio switch
	if (embed_area_width.length >= 1 && embed_area_height.length >= 1)
	{
	    var ratio_x = embed_area_width;
	    var ratio_y = embed_area_height;
	    var embed_area_width_min = embed_area_width;
        var embed_area_height_min = embed_area_height;
        var embed_area_width_animat = embed_area_width;
        var embed_area_height_animat = embed_area_height;
	}
	else
	{
	    var img_edited_q_xy = document.getElementById('im_edited');
	    var ratio_x = img_edited_q_xy.width;
	    var ratio_y = img_edited_q_xy.height;
	}

    if (size_ratio_option == 'ratio')
    {
        if (document.im_edit_f.im_ratio.checked==true)
        {
		    document.im_edit_f.im_size_to_area.checked=false;
		    document.getElementById('im_height').value='';
            document.getElementById('im_height').setAttribute('disabled', 'disabled');
            document.getElementById('im_width').removeAttribute('disabled');
            document.getElementById('im_height_wrap').style.display='none';

            if (im_crop_area != null)
		    {
			    im_crop_area.setOptions({ allowResize: true });
			    im_crop_area.setOptions({ minSize: [0, 0] });
			    im_crop_area.setOptions({ maxSize: [0, 0] });
			    im_crop_area.setOptions({ aspectRatio: ratio_x / ratio_y });
		    }
        }
        else
        {
            document.getElementById('im_height').removeAttribute('disabled');
            document.getElementById('im_height_wrap').style.display='block';

            if (im_crop_area != null)
		    {
			    im_crop_area.setOptions({ allowResize: true });
			    im_crop_area.setOptions({ minSize: [0, 0] });
			    im_crop_area.setOptions({ maxSize: [0, 0] });
			    im_crop_area.setOptions({ aspectRatio: 0 });
			}
        }
    }
    else if (size_ratio_option == 'size')
    {
        if (document.im_edit_f.im_size_to_area.checked==true)
        {
		    document.im_edit_f.im_ratio.checked=false;
		    document.getElementById('im_height_wrap').style.display='block';
		    document.getElementById('im_height').setAttribute('disabled', 'disabled');
		    document.getElementById('im_width').setAttribute('disabled', 'disabled');

		    document.getElementById('im_width').value=embed_area_width;
		    document.getElementById('im_height').value=embed_area_height;

		    if (im_crop_area != null)
		    {
			    im_crop_area.setOptions({ aspectRatio: 0 });
			    im_crop_area.setOptions({ allowResize: false });
			    im_crop_area.setOptions({ minSize: [embed_area_width, embed_area_height] });
			    im_crop_area.setOptions({ maxSize: [embed_area_width, embed_area_height] });
			    im_crop_area.animateTo([100, 100, embed_area_width, embed_area_height]);
		    }
	    }
	    else
	    {
            document.getElementById('im_height').removeAttribute('disabled');
            document.getElementById('im_width').removeAttribute('disabled');

            if (im_crop_area != null)
		    {
			    im_crop_area.setOptions({ allowResize: true });
			    im_crop_area.setOptions({ minSize: [0, 0] });
			    im_crop_area.setOptions({ maxSize: [0, 0] });
			    im_crop_area.setOptions({ aspectRatio: 0 });
		    }
	    }
    }

    if (document.getElementById('crop_but').value=='apply crop')
	{
		document.getElementById('size_input_sect').setAttribute('class', 'img_editor_but_inp');
		document.getElementById('crop_but').setAttribute('class', 'img_editor_but img_editor_but_red');
    	document.getElementById('resize_but').setAttribute('class', 'img_editor_but');
    	document.getElementById('keep_proportion_of').innerHTML='('+keep_proportion_of_obj+')';
	}
	else
	{
		document.getElementById('crop_but').setAttribute('class', 'img_editor_but img_editor_but_selected');
    	document.getElementById('resize_but').setAttribute('class', 'img_editor_but img_editor_but_selected');
    	document.getElementById('keep_proportion_of').innerHTML='(image)';
	}
}


function set_cur_pos(pos) {

	document.getElementById('crop_area_width').value=pos.w;
	document.getElementById('crop_area_height').value=pos.h;
	document.getElementById('crop_area_pos_left').value=pos.x;
	document.getElementById('crop_area_pos_top').value=pos.y;


	var cur_crop_area_width = document.getElementById('crop_area_width').value;
	var cur_crop_area_height = document.getElementById('crop_area_height').value;
	var embed_area_width = document.getElementById('embed_area_width').value;
	var embed_area_height = document.getElementById('embed_area_height').value;

	//crop area hot handle indicators
	if (embed_area_height != '' && im_crop_area != null)
	{
		if (Number(cur_crop_area_height) < Number(embed_area_height))
		{
			if ($('#jcrop_mid_hor_s').not('.jcrop_hot'))
			{
				document.getElementById('jcrop_mid_hor_s').setAttribute('onmouseover', 'crop_im_size_alert(this.id, \'on\');');
				document.getElementById('jcrop_mid_hor_n').setAttribute('onmouseover', 'crop_im_size_alert(this.id, \'on\');');
				document.getElementById('jcrop_mid_hor_s').setAttribute('onmouseout', 'crop_im_size_alert(this.id, \'off\');');
				document.getElementById('jcrop_mid_hor_n').setAttribute('onmouseout', 'crop_im_size_alert(this.id, \'off\');');
				document.getElementById('jcrop_mid_hor_s').className='jcrop-handle jcrop_hot';
				document.getElementById('jcrop_mid_hor_n').className='jcrop-handle jcrop_hot';
			}
		}
		else
		{
			document.getElementById('jcrop_mid_hor_s').removeAttribute('onmouseover');
			document.getElementById('jcrop_mid_hor_n').removeAttribute('onmouseover');
			document.getElementById('jcrop_mid_hor_s').removeAttribute('onmouseout');
			document.getElementById('jcrop_mid_hor_n').removeAttribute('onmouseout');
			document.getElementById('jcrop_mid_hor_s').className='jcrop-handle';
			document.getElementById('jcrop_mid_hor_n').className='jcrop-handle';
		}

		if (Number(cur_crop_area_width) < Number(embed_area_width))
		{
			if ($('#jcrop_mid_vert_e').not('.jcrop_hot'))
			{
				document.getElementById('jcrop_mid_vert_e').setAttribute('onmouseover', 'crop_im_size_alert(this.id, \'on\');');
				document.getElementById('jcrop_mid_vert_w').setAttribute('onmouseover', 'crop_im_size_alert(this.id, \'on\');');
				document.getElementById('jcrop_mid_vert_e').setAttribute('onmouseout', 'crop_im_size_alert(this.id, \'off\');');
				document.getElementById('jcrop_mid_vert_w').setAttribute('onmouseout', 'crop_im_size_alert(this.id, \'off\');');
				document.getElementById('jcrop_mid_vert_e').className='jcrop-handle jcrop_hot';
				document.getElementById('jcrop_mid_vert_w').className='jcrop-handle jcrop_hot';
			}
		}
		else
		{
			document.getElementById('jcrop_mid_vert_e').removeAttribute('onmouseover');
			document.getElementById('jcrop_mid_vert_w').removeAttribute('onmouseover');
			document.getElementById('jcrop_mid_vert_e').removeAttribute('onmouseout');
			document.getElementById('jcrop_mid_vert_w').removeAttribute('onmouseout');
			document.getElementById('jcrop_mid_vert_e').className='jcrop-handle';
			document.getElementById('jcrop_mid_vert_w').className='jcrop-handle';
		}
	}
}


function crop_im_size_alert(div_id, opt_switch) {

	var top_adj;
	var orientation = div_id.substr(0, 14) == 'jcrop_mid_vert' ? 'width' : 'height';

	if (opt_switch == 'on')
	{
		if (div_id == 'jcrop_mid_vert_w' || div_id == 'jcrop_mid_vert_e')
		{
			top_adj = 44;
		}
		else if (div_id == 'jcrop_mid_hor_s')
		{
			top_adj = -20;
		}
		else
		{
			top_adj = 36;
		}

		var top_pos = document.getElementById(div_id).style.top.split('p');
		var left_pos = document.getElementById(div_id).style.left.split('p');
		var top_pos_adj = Number(top_pos[0]) - Number(top_adj);
		var left_pos_adj = Number(left_pos[0]) - 61;

		$('<div id="crop_hot_alert" style="top:'+top_pos_adj+'px;left:'+left_pos_adj+'px;">Crop '+orientation+' is smaller<br />than embed area '+orientation+'!</div>').insertAfter('#'+div_id);
	}
	else
	{
		$('#crop_hot_alert').remove();
	}
}


function apply_crop() {

	var area_q = document.im_edit_f.im_size_to_area.checked==true ? 'embed' : 'crop';
	var crop_width = document.getElementById(area_q+'_area_width').value;
	var crop_height = document.getElementById(area_q+'_area_height').value;
	var crop_x = document.getElementById('crop_area_pos_left').value;
	var crop_y = document.getElementById('crop_area_pos_top').value;

	img_process('cropImage', crop_width, crop_height, crop_x, crop_y);
}


function cleanup_crop() {

	if (im_crop_area != null)
	{
		im_crop_area.destroy();
	}

	document.getElementById('crop_area_width').value='';
	document.getElementById('crop_area_height').value='';
	document.getElementById('crop_area_pos_left').value='';
	document.getElementById('crop_area_pos_top').value='';
	document.getElementById('crop_but').setAttribute('onclick', 'crop_init();');
	document.getElementById('crop_but').setAttribute('class', 'img_editor_but');
    document.getElementById('size_input_sect').setAttribute('class', 'img_editor_but_inp img_editor_inp_selected');
	document.getElementById('crop_but').setAttribute('value', 'crop');
	document.getElementById('cancel_crop_but').style.display='none';
	document.getElementById('im_height_wrap').style.display='block';
	document.im_edit_f.im_ratio.checked=false;
	document.im_edit_f.im_size_to_area.checked=false;
	document.getElementById('keep_proportion_of').innerHTML='(image)';
	document.getElementById('im_width').removeAttribute('disabled');
	document.getElementById('im_height').removeAttribute('disabled');
}


function img_process_revert() {

	var im_path_orig = document.getElementById('orig_image_path').value;

	if (document.getElementById('image_editor_process').value >= '1')
	{
		if (image_object.readystate != 4)
		{
			image_object.abort();
			stop_current_process();
		}
	}

	var cur_version_history = document.getElementById('version_history').value;
	var new_version_history = cur_version_history * -1;

	document.getElementById('cur_max_history').value='-1';
	img_process('history', new_version_history, '', '', '');
}


function swap_images(src, im_path_orig) {

	if (src.split('?')[0] == im_path_orig)
	{
	    var new_image_url = src;
	}
	else
	{
	    var new_image_url = image_editor_path+src;
	}

	document.getElementById('im_edited_wrap_img').innerHTML='<img src="'+new_image_url+'" alt="" id="im_edited_tmp" />';

	$('#im_edited_tmp').fadeIn(300, function() {
    	$('#im_edited_tmp').attr('id', 'im_edited');
  	});
}


function switch_img_controll(cur_id) {

	$('.img_editor_control_switch').removeClass('img_editor_but_selected');
	$('#more_effects').fadeOut(300);

	$('.img_editor_control_section:not(#'+cur_id+'_sect)').slideUp(300);

	$('#'+cur_id+'_sect').slideToggle(300, function() {

		if ($('#'+cur_id+'_sect').is(':visible'))
		{
			$('#'+cur_id).addClass('img_editor_but_selected');

			if (cur_id == 'image_effects')
			{
			    $('#more_effects').fadeIn(120);
			}
		}
	});
}


function effects_show(opt_switch) {

    if (opt_switch == 'more')
    {
        $('#more_effects').fadeOut(300);
        $('#effects_lev_0').fadeOut(300, function() {
            document.getElementById('more_effects').setAttribute('class', 'less_effects_but');
            document.getElementById('more_effects').setAttribute('onclick', 'effects_show(\'less\');');
            document.getElementById('more_effects').setAttribute('value', 'less effects');
            $('#effects_lev_1').fadeIn(300);
            $('#more_effects').fadeIn(300);
        });
    }
    else if (opt_switch == 'less')
    {
        $('#more_effects').fadeOut(300);
        $('#effects_lev_1').fadeOut(300, function() {
            document.getElementById('more_effects').setAttribute('class', 'more_effects_but');
            document.getElementById('more_effects').setAttribute('onclick', 'effects_show(\'more\');');
            document.getElementById('more_effects').setAttribute('value', 'more effects');
            $('#effects_lev_0').fadeIn(300);
            $('#more_effects').fadeIn(300);
        });
    }
}


function input_im_size() {

	var temp_height = document.getElementById('im_height').value;
	var temp_height_clean = temp_height.replace(/([^0-9])/g,'');
	var temp_width = document.getElementById('im_width').value;
	var temp_width_clean = temp_width.replace(/([^0-9])/g,'');


	if (temp_height != temp_height_clean)
	{
	    document.getElementById('im_height').value=temp_height_clean;
	}
	if (temp_width != temp_width_clean)
	{
	    document.getElementById('im_width').value=temp_width_clean;
	}


	if (temp_height.length >= 1 || temp_width.length >= 1)
	{
		document.getElementById('size_input_sect').setAttribute('class', 'img_editor_but_inp img_editor_inp_selected');
		document.getElementById('resize_but').setAttribute('class', 'img_editor_but img_editor_but_selected');
		document.getElementById('crop_but').setAttribute('class', 'img_editor_but');

		if (document.getElementById('crop_but').value=='apply crop')
		{
			cleanup_crop();
		}
	}
	else if (temp_height.length == 0 && temp_width.length == 0)
	{
		document.getElementById('resize_but').setAttribute('class', 'img_editor_but');
	}

	return false;
}


function blur_img_switch() {

	if (document.getElementById('blur_switch').getAttribute('class') == 'img_editor_radial_off')
	{
		document.getElementById('blur_but').setAttribute('onclick', 'img_process(\'radialBlurImage\', 2, \'\', \'\', \'\');');
		document.getElementById('blur_but').setAttribute('class', 'img_editor_but img_editor_but_selected');
		document.getElementById('blur_switch').setAttribute('class', 'img_editor_radial_on');
	}
	else
	{
		document.getElementById('blur_but').setAttribute('onclick', 'img_process(\'blurImage\', 2, 1, \'\', \'\');');
		document.getElementById('blur_but').setAttribute('class', 'img_editor_but');
		document.getElementById('blur_switch').setAttribute('class', 'img_editor_radial_off');
	}
}


function custom_angle_set() {

    var temp_angle = document.getElementById('custom_angle').value;
	var temp_angle_clean = temp_angle.replace(/([^0-9\-])/g,'');

	if (temp_angle != temp_angle_clean)
	{
	    document.getElementById('custom_angle').value=temp_angle_clean;
	}


	if (document.getElementById('custom_angle').value.length >= 1)
    {
	    document.getElementById('custom_angle_sect').setAttribute('class', 'custom_angle_sect img_editor_inp_selected');
        document.getElementById('custom_angle_but').setAttribute('class', 'img_editor_but img_editor_but_selected');
        document.getElementById('custom_angle_but').setAttribute('value', 'apply angle');
    }
    else
    {
        document.getElementById('custom_angle_sect').setAttribute('class', 'custom_angle_sect');
        document.getElementById('custom_angle_but').setAttribute('class', 'img_editor_but');
        document.getElementById('custom_angle_but').setAttribute('value', 'custom angle');
    }
}


function custom_angle_apply() {

    if (document.getElementById('custom_angle').value.length <= 0)
    {
        document.getElementById('custom_angle_sect').setAttribute('class', 'custom_angle_sect img_editor_inp_selected');
        document.getElementById('custom_angle_but').setAttribute('class', 'img_editor_but img_editor_but_selected');
        var angle_not_set_message = '<div class="im_editor_warning">Please set angle first.</div>';
        set_img_editor_alert(angle_not_set_message);
        document.getElementById('custom_angle').focus();
        return;
    }
    else
    {
        var q_angle = document.getElementById('custom_angle').value;
        img_process('rotateImage', q_angle, '', '', '');

        document.getElementById('custom_angle').value='';
        document.getElementById('custom_angle_sect').setAttribute('class', 'custom_angle_sect');
        document.getElementById('custom_angle_but').setAttribute('class', 'img_editor_but');
        document.getElementById('custom_angle_but').setAttribute('value', 'custom angle');
    }
}


function im_editor_to_edit(mode_switch) {

    $('#edit_or_replace').hide(600);

    if (mode_switch == 'replace')
    {
        load_new_image('show', '');
    }
}


function large_version_preview(opt_switch) {

    if (opt_switch == 'hide')
    {
        $('#large_version_popup').fadeOut(300, function() {
            $('#large_version_popup').remove();
        });
    }
    else
    {
        var preview_img_src = document.getElementById('im_edited').src;
	    var preview_img_height = document.getElementById('image_info_dimention_h').innerHTML;
	    var preview_img_width = document.getElementById('image_info_dimention_w').innerHTML;
	    var window_width = $(window).width();
        var window_height = $(window).height();
        var preview_img_max_width = window_width - 200;
        var preview_img_max_height = window_height - 200;

        if (preview_img_height > preview_img_max_height || preview_img_width > preview_img_max_width)
        {
            var preview_img_margin_top = (window_height - preview_img_max_height) / 2 - 50;
        }
        else
        {
            var preview_img_margin_top = (window_height - preview_img_height) / 2 - 50;
        }

        var large_preview_div = '<div id="large_version_popup" ' +
                                'style="width:'+window_width+'px;height:'+window_height+'px;" '+
                                'onclick="large_version_preview(\'hide\');">' +
                                '<div id="large_version_popup_overlay"></div>' +
                                '<img src="'+preview_img_src+'" alt="" ' +
                                'class="large_version_popup_img" ' +
                                'style="max-width:'+preview_img_max_width+'px;' +
                                'max-height:'+preview_img_max_height+'px;' +
                                'margin:'+preview_img_margin_top+'px auto;' +
                                '" />' +
                                '</div>';

        $(large_preview_div).insertBefore($('#image_editor'));
        $('#large_version_popup').fadeIn(300);
    }
}


function external_url_try() {

	var external_img_url = '';
	var user_name = document.getElementById('user_name').value;
	var image_editor_process = document.getElementById('image_editor_process').value;
	var external_img_url_qq = document.getElementById('external_img_url').value;

	if (external_img_url_qq.substr(0, 8) == 'uploads/')
	{
		external_img_url = 'tmp/'+user_name+'/'+external_img_url_qq;
	}
	else
	{
		external_img_url = external_img_url_qq;
	}

	//kill curently running requests prior starting a new one
	if (image_editor_process >= '1')
	{
        try_image_url.abort();
        document.getElementById('image_editor_process').value='';
        external_url_try();
        return;
    }


	try_image_url = $.ajax({
		type: 'POST',
		url: image_editor_path+'process_external_img.php',
		data:
		{
			user_name: user_name,
			image_path: encodeURI(external_img_url)
		},
		beforeSend: function(try_image_url)
		{
            im_editor_process_time_start();
            document.getElementById('ext_url_try_now').style.display='none';
		    document.getElementById('ext_url_loading').style.display='block';
		    setTimeout("im_editor_loading_message()", 2000);
		},
  		success: function(try_result_array)
		{
		    var try_result = jQuery.parseJSON(try_result_array);
		    var new_image_path = image_editor_path+try_result.new_image_path;
		    var result_answer = try_result.answer;
		    var response_message = try_result.response_message;
		    var new_history = try_result.history;
			var new_width = try_result.width;
			var new_height = try_result.height;
			var new_resolution = try_result.resolution;
			var new_file_size = try_result.file_size;
			var action_name = try_result.action_name;
		    var cur_response_message = document.getElementById('image_url_row_message').innerHTML;

		    document.getElementById('ext_url_try_now').style.display='block';
		    document.getElementById('ext_url_loading').style.display='none';

		    if (result_answer == true)
		    {
			    document.getElementById('im_edited').src=new_image_path+'?q='+Math.random();
			    document.getElementById('image_info_filename').value=new_image_path.split('/').pop();
			    document.getElementById('image_info_dimention_w').innerHTML=new_width;
			    document.getElementById('image_info_dimention_h').innerHTML=new_height;
			    document.getElementById('image_info_resolution').innerHTML=new_resolution;
			    document.getElementById('image_info_size').innerHTML=new_file_size;
			    document.getElementById('image_file_info_messages').innerHTML=action_name;
			    document.getElementById('embed_area_alert').value='';
			    document.getElementById('image_file_info_alerts').style.display='none';


			    //history and hidden values
			    document.getElementById('orig_image_path').value=new_image_path;
                document.getElementById('version_history').value='0';
                document.getElementById('cur_max_history').value='0';

                document.getElementById('history_revert').removeAttribute('onclick');
                document.getElementById('history_revert').setAttribute('class', 'img_editor_but_revert_disabled');

                document.getElementById('history_undo').removeAttribute('onclick');
                document.getElementById('history_undo').setAttribute('class', 'img_editor_but_undo_disabled');

                document.getElementById('history_redo').removeAttribute('onclick');
                document.getElementById('history_redo').setAttribute('class', 'img_editor_but_redo_disabled');
		    }

		    if (response_message != cur_response_message)
		    {
		        $('#image_url_row_message').fadeOut(120, function () {

		            document.getElementById('image_url_row_message').innerHTML=response_message;
		            $('#image_url_row_message').fadeIn(120);
		        });
		    }

		    document.getElementById('image_editor_process').value='';
		}
	});
}


function im_editor_process_time_start() {

	var time_now = new Date;
	var unixtime_ms = time_now.getTime();
	var unixtime = parseInt(unixtime_ms / 1000);
	document.getElementById('image_editor_process').value=unixtime;
}


function im_editor_loading_message() {

	var time_q = new Date;
	var unixtime_ms_q = time_q.getTime();
	var unixtime_now = parseInt(unixtime_ms_q / 1000);
	var cur_process_start_time = document.getElementById('image_editor_process').value;

	if (cur_process_start_time != '')
	{
		if (cur_process_start_time < unixtime_now)
		{
			$('#image_url_row_message').fadeOut(120, function () {
				document.getElementById('image_url_row_message').innerHTML='Loading Image...';
				$('#image_url_row_message').fadeIn(120);
			});
		}
	}
}


function external_url_cancel() {

    document.getElementById('external_img_url').value='';
    external_url_try();
}


function set_img_editor_alert(alert) {

    document.getElementById('image_file_info_alerts').innerHTML=alert;
    $('#image_file_info_alerts').fadeIn(600);
}


function im_editor_coll_switch(collection_id) {

    load_new_image('reload_collection', collection_id);
}


function stop_current_process() {

	document.getElementById('image_file_info_messages').innerHTML='Pocess stopped';
	document.getElementById('image_editor_process').value='';
}


function blink_image_file_info_alerts(alert) {

	$('#image_file_info_alerts').fadeOut(220, function() {
		document.getElementById('image_file_info_alerts').innerHTML=alert;
		$('#image_file_info_alerts').fadeIn(120);
	});
}


function img_size_check(user_set_width, user_set_height, embed_area_width, embed_area_height) {

	var minimum_size_message = '<div class="im_editor_warning">Warning:</div>Minimum allowed image size is 20x20.<br /><br />Please adjust image size.';
	var maximum_size_message = '<div class="im_editor_warning">Warning:</div>For optimum performance, image size should not exceed 2000x2000.<br /><br />Please adjust image size.';
	var zero_size_message = '<div class="im_editor_warning">Please set image size first.</div>';
	var image_smaller_than_area = '<div class="im_editor_warning">Warning:</div>Image is smaller than the area it is embedded to.<br /><br />Image may get distorted.';
	var embed_area_alert = document.getElementById('embed_area_alert').value;

	if (user_set_width.length == 0 && user_set_height.length == 0)
	{
	    set_img_editor_alert(zero_size_message);
	    return false;
	}

	if (Number(user_set_width) >= 2001 || Number(user_set_height) >= 2001)
	{
	    set_img_editor_alert(maximum_size_message);
	    return false;
	}

	if (Number(user_set_width) <= 19 && user_set_height.length == 0)
	{
	    set_img_editor_alert(minimum_size_message);
	    return false;
	}

	if (Number(user_set_height) <= 19 && user_set_width.length == 0)
	{
	    set_img_editor_alert(minimum_size_message);
	    return false;
	}

	if (user_set_width.length != 0 && user_set_height.length != 0)
	{
	    if (Number(user_set_width) <= 19 || Number(user_set_height) <= 19)
	    {
	    	set_img_editor_alert(minimum_size_message);
	    	return false;
	    }
	}


	//Image is smaller than the area it is embedded to alert
	if (embed_area_width.length >= 1 && embed_area_alert.length == 0)
	{
	    if (user_set_width != '' && user_set_height == '')
	    {
	    	if (Number(user_set_width) < Number(embed_area_width))
	    	{
	        	set_img_editor_alert(image_smaller_than_area);
	        	document.getElementById('embed_area_alert').value='1';
	        }
	    }
	    else if (user_set_width == '' && user_set_height != '')
	    {
	    	if (Number(user_set_height) < Number(embed_area_height))
	    	{
	        	set_img_editor_alert(image_smaller_than_area);
	        	document.getElementById('embed_area_alert').value='1';
	        }
	    }
	    else
	    {
	    	if (Number(user_set_width) < Number(embed_area_width) || Number(user_set_height) < Number(embed_area_height))
	    	{
	        	set_img_editor_alert(image_smaller_than_area);
	        	document.getElementById('embed_area_alert').value='1';
	    	}
	    }
	}

	return true;
}


function im_editor_close() {

	if (document.getElementById('image_editor_process').value >= '1')
	{
		image_object.abort();
		stop_current_process();
	}

	$('#image_editor').fadeOut(300, function() {
		im_editor_cleanup();
	});
}


function im_editor_cleanup() {

	$('#img_editor_pre_wrap').remove();

	var overflow_div = $('#whole_page_wrap').size();

	if (overflow_div >= 1)
	{
	    $('#whole_page_wrap').fadeOut(120);
	}
}


function month_days(day,month,year) {

	if (month.length==0 || year.length==0)
	{
		return;
	}

	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null)
	{
		alert ('Your browser does not support AJAX!');
		return;
	}

	var url=image_editor_path+'days_in_month.php';
	url=url+'?day='+day;
	url=url+'&month='+month;
	url=url+'&year='+year;
	url=url+'&sid='+Math.random();
	xmlHttp.onreadystatechange=return_days_in_month;
	xmlHttp.open('GET',url,true);
	xmlHttp.send(null);
}


function return_days_in_month() {

	if (xmlHttp.readyState==4)
	{
		document.getElementById('dayselect').innerHTML=xmlHttp.responseText;
	}
}


function GetXmlHttpObject() {

	var xmlHttp=null;
	try
	{
		xmlHttp=new XMLHttpRequest();
	}
	catch(e)
	{
		try
		{
			xmlHttp=new ActiveXObject('Msxml2.XMLHTTP');
		}
		catch(e)
		{
			xmlHttp=new ActiveXObject('Microsoft.XMLHTTP');
		}
	}
	return xmlHttp;
}


function select_option_value(select, value) {

	var i = 0;
	var end = select.options.length;

	while(i < end)
	{
		if (select.options[i].value==value)
		{
			select.options[i].selected=true;
			select.selectedIndex=i;
		}
		else
		{
			select.options[i].selected=false;
		}
	i++;
	}
}


function save_curent_version() {

    var cur_img_path = document.getElementById('im_edited').src.split('?q=')[0];

    if (document.getElementById('image_editor_process').value >= '1')
	{
		blink_image_file_info_alerts(alert_can_not_do_while_in_process);
		return;
	}

    cleanup_crop();

    im_editor_process_time_start();
    document.getElementById('im_edited_save').removeAttribute('onclick');
    document.getElementById('im_edited_save').className='img_editor_but_save_disabled';
    document.getElementById('image_file_info_messages').innerHTML='<img src="'+image_editor_path+'img/loading.gif" alt="" id="images_process_loading" /><div id="process_stop">saving...</div>';

	document.getElementById('image_temp_file').value=cur_img_path;

    save_cur_image = $.post('../../../index.php', $('#im_edit_f').serialize()).success(function(data)
	{
	    var image_info = jQuery.parseJSON(data);
		var new_object_id = image_info.new_object_id;
		var base_name = image_info.base_name;
		var im_width = image_info.im_width;
		var im_height = image_info.im_height;
		var im_title = image_info.im_title;
		var img_id_inp = image_info.img_id_inp;

		var asset_list_thumb_id = img_id_inp.replace('ap_', 'al_');
		var user_name = image_info.user_name;
		var editor_object_id = image_info.editor_object_id;
		var init_image_path = image_info.init_image_path;
		var new_img_id_inp = 'ap_'+new_object_id;
		var action_switch = document.getElementById('action_switch').value;


		//assure long filenames will not break the asset preview screen...
		var clean_im_title = (im_title == im_title.substr(0, 28) ? im_title : im_title.substr(0, 28) + '...');
		var clean_base_name = (base_name == base_name.substr(0, 28) ? base_name : base_name.substr(0, 28) + '...');

		var new_image_url='http://memberdata.s3.amazonaws.com/'+user_name.substr(0,2)+'/'+user_name+'/photos/'+base_name;


		//only do this if we are in asset_manager->photos->asset_preview
		if (img_id_inp.substr(0,3) == 'ap_')
		{

//start updating the page....

			//title & filename
			document.getElementById('asset_prev_im_title').innerHTML=clean_im_title;
			document.getElementById('asset_prev_im_filename').innerHTML=clean_base_name;


			//only do this part if image was edited (image file was changed)...
			if (init_image_path != new_image_url)
			{
	    		//edit link
	    		var cur_edit_link_onclick = document.getElementById('asset_preview_edit_img_link').getAttribute('onclick');
	    		var new_edit_link_onclick = cur_edit_link_onclick.replace(img_id_inp, new_img_id_inp);
	    		document.getElementById('asset_preview_edit_img_link').setAttribute('onclick', new_edit_link_onclick);

	    		//actual image
	    		var cur_img = document.getElementById(img_id_inp);
	    		cur_img.setAttribute('id', new_img_id_inp);
	    		document.getElementById(new_img_id_inp).setAttribute('class', 'preview_pic_edited');
	    		document.getElementById(new_img_id_inp).removeAttribute('style');
	    		document.getElementById(new_img_id_inp).src=new_image_url+'?q='+Math.random();


	    		//thumbnail in the asset list
	    		thumb_holder_div = document.getElementById(asset_list_thumb_id).parentNode.id;


            	var old_thumb_onclick = document.getElementById(thumb_holder_div).getAttribute('onclick');
            	var new_thumb_id_inp = new_img_id_inp.replace('ap_', 'al_');
            	var old_base_name = init_image_path.split('/').pop().replace('_lr', '');

            	var new_thumb_onclick_object_id_fix = old_thumb_onclick.replace(editor_object_id, new_object_id);
            	var new_thumb_onclick = new_thumb_onclick_object_id_fix.replace(old_base_name, base_name);

            	document.getElementById(thumb_holder_div).setAttribute('onclick', new_thumb_onclick);
            	document.getElementById(thumb_holder_div).removeAttribute('onmouseover');

            	//need to calculate and set margins...
            	var max_numb = 72;	//box where we need to fit the image in...
            	var amount_q;
            	var margin_mame;

            	if (Math.floor(im_width) > Math.floor(im_height))
            	{
            		margin_mame = 'margin-top';
            		amount_q = Number(max_numb) * Number(im_height) / Number(im_width);
            	}
            	else
            	{
            		margin_mame = 'margin-left';
            		amount_q = Number(max_numb) * Number(im_width) / Number(im_height);
            	}

				var amount_q_real = Math.floor(( Number(max_numb) - Number(amount_q) ) / 2);

            	var new_margin = margin_mame + ':' + amount_q_real + 'px;';
            	var new_thumb_style = 'max-height:72px;max-width:72px;'+new_margin;

            	document.getElementById(asset_list_thumb_id).setAttribute('style', new_thumb_style);


            	//change thumb src & id
            	document.getElementById(asset_list_thumb_id).src=new_image_url+'?q='+Math.random();
				document.getElementById(asset_list_thumb_id).setAttribute('id', new_thumb_id_inp);
			}
		}
		else if (action_switch == 'input')
		{
			document.getElementById(img_id_inp).value=new_image_url;
		}
		else
		{
			document.getElementById(asset_list_thumb_id).src=new_image_url+'?q='+Math.random();
		}

		var custom_function_on_close = document.getElementById('custom_function_on_close').value;




//custom function start
		if (custom_function_on_close == 's101_insert_image')
		{
		    s101_insert_image();
		}
		else if (custom_function_on_close == 'replace_cur_thmb')
		{
		    replace_cur_thmb(new_image_url+'?q='+Math.random());
		}
//custom function end






		document.getElementById('image_editor_process').value='';
		im_editor_close();
	});
}


//___________________________________________________________________________________________//
//_________________________________uploader part_____________________________________________//
//___________________________________________________________________________________________//

var imm = imm || {};

imm.extend = function(first, second){
    for (var prop in second){
        first[prop] = second[prop];
    }
};

imm.indexOf = function(arr, elt, from){
    if (arr.indexOf) return arr.indexOf(elt, from);

    from = from || 0;
    var len = arr.length;

    if (from < 0) from += len;

    for (; from < len; from++){
        if (from in arr && arr[from] === elt){
            return from;
        }
    }
    return -1;
};

imm.getUniqueId = (function(){
    var id = 0;
    return function(){ return id++; };
})();

imm.attach = function(element, type, fn){
    if (element.addEventListener){
        element.addEventListener(type, fn, false);
    } else if (element.attachEvent){
        element.attachEvent('on' + type, fn);
    }
};
imm.detach = function(element, type, fn){
    if (element.removeEventListener){
        element.removeEventListener(type, fn, false);
    } else if (element.attachEvent){
        element.detachEvent('on' + type, fn);
    }
};

imm.preventDefault = function(e){
    if (e.preventDefault){
        e.preventDefault();
    } else{
        e.returnValue = false;
    }
};


imm.insertBefore = function(a, b){
    b.parentNode.insertBefore(a, b);
};
imm.remove = function(element){
    element.parentNode.removeChild(element);
};

imm.contains = function(parent, descendant){

    if (parent == descendant) return true;

    if (parent.contains){
        return parent.contains(descendant);
    } else {
        return !!(descendant.compareDocumentPosition(parent) & 8);
    }
};

imm.toElement = (function(){
    var div = document.createElement('div');
    return function(html){
        div.innerHTML = html;
        var element = div.firstChild;
        div.removeChild(element);
        return element;
    };
})();

imm.css = function(element, styles){
    if (styles.opacity != null){
        if (typeof element.style.opacity != 'string' && typeof(element.filters) != 'undefined'){
            styles.filter = 'alpha(opacity=' + Math.round(100 * styles.opacity) + ')';
        }
    }
    imm.extend(element.style, styles);
};

imm.hasClass = function(element, name){
    var re = new RegExp('(^| )' + name + '( |$)');
    return re.test(element.className);
};

imm.addClass = function(element, name){
    if (!imm.hasClass(element, name)){
        element.className += ' ' + name;
    }
};

imm.removeClass = function(element, name){
    var re = new RegExp('(^| )' + name + '( |$)');
    element.className = element.className.replace(re, ' ').replace(/^\s+|\s+$/g, '');
};

imm.setText = function(element, text){
    element.innerHTML = text;
};

imm.children = function(element){
    var children = [],
    child = element.firstChild;

    while (child){
        if (child.nodeType == 1){
            children.push(child);
        }
        child = child.nextSibling;
    }

    return children;
};

imm.getByClass = function(element, className){
    if (element.querySelectorAll){
        return element.querySelectorAll('.' + className);
    }

    var result = [];
    var candidates = element.getElementsByTagName('*');
    var len = candidates.length;

    for (var i = 0; i < len; i++){
        if (imm.hasClass(candidates[i], className)){
            result.push(candidates[i]);
        }
    }
    return result;
};

imm.obj2url = function(obj, temp, prefixDone){
    var uristrings = [],
        prefix = '&',
        add = function(nextObj, i){
            var nextTemp = temp
                ? (/\[\]$/.test(temp)) // prevent double-encoding
                   ? temp
                   : temp+'['+i+']'
                : i;
            if ((nextTemp != 'undefined') && (i != 'undefined')) {
                uristrings.push(
                    (typeof nextObj === 'object')
                        ? imm.obj2url(nextObj, nextTemp, true)
                        : (Object.prototype.toString.call(nextObj) === '[object Function]')
                            ? encodeURIComponent(nextTemp) + '=' + encodeURIComponent(nextObj())
                            : encodeURIComponent(nextTemp) + '=' + encodeURIComponent(nextObj)
                );
            }
        };

    if (!prefixDone && temp) {
      prefix = (/\?/.test(temp)) ? (/\?$/.test(temp)) ? '' : '&' : '?';
      uristrings.push(temp);
      uristrings.push(imm.obj2url(obj));
    } else if ((Object.prototype.toString.call(obj) === '[object Array]') && (typeof obj != 'undefined') ) {
        // we wont use a for-in-loop on an array (performance)
        for (var i = 0, len = obj.length; i < len; ++i){
            add(obj[i], i);
        }
    } else if ((typeof obj != 'undefined') && (obj !== null) && (typeof obj === 'object')){
        // for anything else but a scalar, we will use for-in-loop
        for (var i in obj){
            add(obj[i], i);
        }
    } else {
        uristrings.push(encodeURIComponent(temp) + '=' + encodeURIComponent(obj));
    }

    return uristrings.join(prefix)
                     .replace(/^&/, '')
                     .replace(/%20/g, '+');
};

imm.FileUploaderBasic = function(o){
    this._options = {
        // set to true to see the server response
        debug: false,
        action: 'upload',
        params: {},
        button: null,
        multiple: false,
        maxConnections: 3,
        sizeLimit: 0,
        minSizeLimit: 0,
        // events
        // return false to cancel submit
        onSubmit: function(id, fileName){},
        onProgress: function(id, fileName, loaded, total){},
        onComplete: function(id, fileName, responseJSON){},
        onCancel: function(id, fileName){},
        // messages
        messages: {
            typeError: "{file} has invalid extension. Only {extensions} are allowed.",
            sizeError: "{file} is too large, maximum file size allowed is {sizeLimit}.",
            minSizeError: "{file} is too small, minimum file size allowed is {minSizeLimit}.",
            emptyError: "{file} is empty. Upload has been canceled.",
            onLeave: "The files are being uploaded! Navigating away from this page will result in data loss."
        },
        showMessage: function(message){
            alert(message);
        }
    };
    imm.extend(this._options, o);
    this._filesInProgress = 0;
    this._handler = this._createUploadHandler();

    if (this._options.button){
        this._button = this._createUploadButton(this._options.button);
    }

    this._preventLeaveInProgress();
};

imm.FileUploaderBasic.prototype = {
    setParams: function(params){
        this._options.params = params;
    },
    getInProgress: function(){
        return this._filesInProgress;
    },
    _createUploadButton: function(element){
        var self = this;

        return new imm.UploadButton({
            element: element,
            multiple: this._options.multiple && imm.UploadHandlerXhr.isSupported(),
            onChange: function(input){
                self._onInputChange(input);
            }
        });
    },
    _createUploadHandler: function(){
        var self = this,
            handlerClass;

        if(imm.UploadHandlerXhr.isSupported()){
            handlerClass = 'UploadHandlerXhr';
        } else {
            handlerClass = 'UploadHandlerForm';
        }

        var handler = new imm[handlerClass]({
            debug: this._options.debug,
            action: this._options.action,
            maxConnections: this._options.maxConnections,
            onProgress: function(id, fileName, loaded, total){
                self._onProgress(id, fileName, loaded, total);
                self._options.onProgress(id, fileName, loaded, total);
            },
            onComplete: function(id, fileName, result){
                self._onComplete(id, fileName, result);
                self._options.onComplete(id, fileName, result);
            },
            onCancel: function(id, fileName){
                self._onCancel(id, fileName);
                self._options.onCancel(id, fileName);
            }
        });

        return handler;
    },
    _preventLeaveInProgress: function(){
        var self = this;

        imm.attach(window, 'beforeunload', function(e){
            if (!self._filesInProgress){return;}

            var e = e || window.event;
            // for ie, ff
            e.returnValue = self._options.messages.onLeave;
            // for webkit
            return self._options.messages.onLeave;
        });
    },
    _onSubmit: function(id, fileName){
        this._filesInProgress++;
    },
    _onProgress: function(id, fileName, loaded, total){
    },
    _onComplete: function(id, fileName, result){
        this._filesInProgress--;
        if (result.error){
            this._options.showMessage(result.error);
        }
    },
    _onCancel: function(id, fileName){
        this._filesInProgress--;
    },
    _onInputChange: function(input){
        if (this._handler instanceof imm.UploadHandlerXhr){
            this._uploadFileList(input.files);
        } else {
            if (this._validateFile(input)){
                this._uploadFile(input);
            }
        }
        this._button.reset();
    },
    _uploadFileList: function(files){
        for (var i=0; i<files.length; i++){
            if ( !this._validateFile(files[i])){
                return;
            }
        }

        for (var i=0; i<files.length; i++){
            this._uploadFile(files[i]);
        }
    },
    _uploadFile: function(fileContainer){
        var id = this._handler.add(fileContainer);
        var fileName = this._handler.getName(id);

        if (this._options.onSubmit(id, fileName) !== false){
            this._onSubmit(id, fileName);
            this._handler.upload(id, this._options.params);
        }
    },
    _validateFile: function(file){
        var name, size;

        if (file.value){
            // it is a file input
            // get input value and remove path to normalize
            name = file.value.replace(/.*(\/|\\)/, '');
        } else {
            // fix missing properties in Safari
            name = file.fileName != null ? file.fileName : file.name;
            size = file.fileSize != null ? file.fileSize : file.size;
        }

        if (! this._isAllowedExtension(name)){
            this._error('typeError', name);
            return false;

        } else if (size === 0){
            this._error('emptyError', name);
            return false;

        } else if (size && this._options.sizeLimit && size > this._options.sizeLimit){
            this._error('sizeError', name);
            return false;

        } else if (size && size < this._options.minSizeLimit){
            this._error('minSizeError', name);
            return false;
        }

        return true;
    },
    _error: function(code, fileName){
        var message = this._options.messages[code];
        function r(name, replacement){ message = message.replace(name, replacement); }

        r('{file}', this._formatFileName(fileName));
        r('{extensions}', this._options.allowedExtensions.join(', '));
        r('{sizeLimit}', this._formatSize(this._options.sizeLimit));
        r('{minSizeLimit}', this._formatSize(this._options.minSizeLimit));

        this._options.showMessage(message);
    },
    _formatFileName: function(name){
        if (name.length > 23){
            name = name.slice(0, 14) + '...' + name.slice(-6);
        }
        return name;
    },
    _isAllowedExtension: function(fileName){
        var ext = (-1 !== fileName.indexOf('.')) ? fileName.replace(/.*[.]/, '').toLowerCase() : '';
        var allowed = this._options.allowedExtensions;

        if (!allowed.length){return true;}

        for (var i=0; i<allowed.length; i++){
            if (allowed[i].toLowerCase() == ext){ return true;}
        }

        return false;
    },
    _formatSize: function(bytes){
        var i = -1;
        do {
            bytes = bytes / 1024;
            i++;
        } while (bytes > 99);

        return Math.max(bytes, 0.1).toFixed(1) + ['kB', 'MB', 'GB', 'TB', 'PB', 'EB'][i];
    }
};

imm.FileUploader = function(o){

    imm.FileUploaderBasic.apply(this, arguments);

    imm.extend(this._options, {
        element: null,
        listElement: null,

        template: '<div class="im_uploader">' +
                		'<div class="im_upload_button" id="im_upload_button">Browse</div>' +
                		'<div class="im_upload_list" id="'+this._options.element.id+'_list"></div>' +
             		'</div>',

        fileTemplate: '<div class="upload_progress">' +
                			'<img src="'+image_editor_path+'img/loading.gif" class="im_upload_cancel" />' +
                			'<span class="im_upload_file"></span>' +
                			'<div class="im_upload_size"></div>' +
                		'</div>',

        classes: {
            button: 'im_upload_button',
            list: 'im_upload_list',

            file: 'im_upload_file',
            spinner: 'im_upload_size',
            size: 'im_upload_size',
            cancel: 'im_upload_cancel',

            success: 'im_upload_success',
            fail: 'im_upload_fail'
        }
    });

    imm.extend(this._options, o);

    this._element = this._options.element;
    this._element.innerHTML = this._options.template;
    this._listElement = this._options.listElement || this._find(this._element, 'list');

    this._classes = this._options.classes;

    this._button = this._createUploadButton(this._find(this._element, 'button'));

    this._bindCancelEvent();
};

imm.extend(imm.FileUploader.prototype, imm.FileUploaderBasic.prototype);

imm.extend(imm.FileUploader.prototype, {

    _find: function(parent, type){
        var element = imm.getByClass(parent, this._options.classes[type])[0];
        if (!element){
            throw new Error('element not found ' + type);
        }

        return element;
    },
    _onSubmit: function(id, fileName) {

        imm.FileUploaderBasic.prototype._onSubmit.apply(this, arguments);
        this._addToList(id, fileName);
    },
    _onProgress: function(id, fileName, loaded, total){
        imm.FileUploaderBasic.prototype._onProgress.apply(this, arguments);

        var item = this._getItemByFileId(id);
        var size = this._find(item, 'size');


//progress bar...
		var cur_zone_id = this._getItemByFileId(id).parentNode.parentNode.parentNode.id;
		var cur_width = document.getElementById(cur_zone_id).offsetWidth - 18;

        var progress_width = Math.round(loaded / total * cur_width) + 'px';
        size.style.display = 'block';
        size.style.width = progress_width;

        var text;

        if (loaded != total) {
            text = Math.round(loaded / total * 100) + '%';
        } else {
            //text = this._formatSize(total);
            text = 'done';
        }

        imm.setText(size, text);
    },
    _onComplete: function(id, fileName, result){
        imm.FileUploaderBasic.prototype._onComplete.apply(this, arguments);

        // mark completed
        var item = this._getItemByFileId(id);
        imm.remove(this._find(item, 'cancel'));
        imm.remove(this._find(item, 'spinner'));

    },
    _addToList: function(id, fileName){
        var item = imm.toElement(this._options.fileTemplate);
        item.immFileId = id;

        var fileElement = this._find(item, 'file');
        this._find(item, 'size').style.display = 'none';

        this._listElement.insertBefore(item, this._listElement.childNodes[0]);
    },
    _getItemByFileId: function(id){
        var item = this._listElement.firstChild;

        // there can't be txt nodes in dynamically created list
        // and we can  use nextSibling
        while (item){
            if (item.immFileId == id) return item;
            item = item.nextSibling;
        }
    },
    _bindCancelEvent: function(){
        var self = this,
            list = this._listElement;

        imm.attach(list, 'click', function(e){
            e = e || window.event;
            var target = e.target || e.srcElement;

            if (imm.hasClass(target, self._classes.cancel)){
                imm.preventDefault(e);

                var item = target.parentNode;
                self._handler.cancel(item.immFileId);
                imm.remove(item);
            }
        });
    }
});

imm.UploadButton = function(o){
    this._options = {
        element: null,
        // if set to true adds multiple attribute to file input
        multiple: false,
        // name attribute of file input
        name: 'file',
        onChange: function(input){}
    };

    imm.extend(this._options, o);

    this._element = this._options.element;

    imm.css(this._element, {
        position: 'relative',
        overflow: 'hidden'
    });

    this._input = this._createInput();
};

imm.UploadButton.prototype = {

    getInput: function(){
        return this._input;
    },
    reset: function(){
        if (this._input.parentNode){
            imm.remove(this._input);
        }

        imm.removeClass(this._element, this._options.focusClass);
        this._input = this._createInput();
    },
    _createInput: function(){
        var input = document.createElement('input');

        if (this._options.multiple){
            input.setAttribute('multiple', 'multiple');
        }

        input.setAttribute('type', 'file');
        input.setAttribute('name', this._options.name);

        imm.css(input, {
            position: 'absolute',
            right: 0,
            top: 0,
            fontFamily: 'Arial',
            fontSize: '118px',
            margin: 0,
            padding: 0,
            cursor: 'pointer',
            opacity: 0
        });

        this._element.appendChild(input);

        var self = this;
        imm.attach(input, 'change', function(){
            self._options.onChange(input);
        });

        imm.attach(input, 'mouseover', function(){
            imm.addClass(self._element, self._options.hoverClass);
        });
        imm.attach(input, 'mouseout', function(){
            imm.removeClass(self._element, self._options.hoverClass);
        });
        imm.attach(input, 'focus', function(){
            imm.addClass(self._element, self._options.focusClass);
        });
        imm.attach(input, 'blur', function(){
            imm.removeClass(self._element, self._options.focusClass);
        });

        if (window.attachEvent){
            input.setAttribute('tabIndex', '-1');
        }

        return input;
    }
};

imm.UploadHandlerAbstract = function(o){
    this._options = {
        debug: false,
        //action: 'upload.php',
        // maximum number of concurrent uploads
        maxConnections: 999,
        onProgress: function(id, fileName, loaded, total){},
        onComplete: function(id, fileName, response){},
        onCancel: function(id, fileName){}
    };
    imm.extend(this._options, o);

    this._queue = [];
    // params for files in queue
    this._params = [];
};
imm.UploadHandlerAbstract.prototype = {
    log: function(str){
        if (this._options.debug && window.console) console.log('[uploader] ' + str);
    },
    add: function(file){},
    upload: function(id, params){
        var len = this._queue.push(id);

        var copy = {};
        imm.extend(copy, params);
        this._params[id] = copy;

        // if too many active uploads, wait...
        if (len <= this._options.maxConnections){
            this._upload(id, this._params[id]);
        }
    },
    cancel: function(id){
        this._cancel(id);
        this._dequeue(id);
    },
    cancelAll: function(){
        for (var i=0; i<this._queue.length; i++){
            this._cancel(this._queue[i]);
        }
        this._queue = [];
    },
    getName: function(id){},
    getSize: function(id){},
    getQueue: function(){
        return this._queue;
    },
    _upload: function(id){},
    _cancel: function(id){},
    _dequeue: function(id){
        var i = imm.indexOf(this._queue, id);
        this._queue.splice(i, 1);

        var max = this._options.maxConnections;

        if (this._queue.length >= max && i < max){
            var nextId = this._queue[max-1];
            this._upload(nextId, this._params[nextId]);
        }
    }
};

imm.UploadHandlerForm = function(o){

    imm.UploadHandlerAbstract.apply(this, arguments);
    this._inputs = {};
};

imm.extend(imm.UploadHandlerForm.prototype, imm.UploadHandlerAbstract.prototype);

imm.extend(imm.UploadHandlerForm.prototype, {
    add: function(fileInput){
        fileInput.setAttribute('name', 'immfile');
        var id = 'imm-upload-handler-iframe' + imm.getUniqueId();

        this._inputs[id] = fileInput;

        // remove file input from DOM
        if (fileInput.parentNode){
            imm.remove(fileInput);
        }

        return id;
    },
    getName: function(id){
        // get input value and remove path to normalize
        return this._inputs[id].value.replace(/.*(\/|\\)/, '');
    },
    _cancel: function(id){
        this._options.onCancel(id, this.getName(id));

        delete this._inputs[id];

        var iframe = document.getElementById(id);
        if (iframe){
            iframe.setAttribute('src', 'javascript:false;');

            imm.remove(iframe);
        }
    },
    _upload: function(id, params){
        var input = this._inputs[id];

        if (!input){
            throw new Error('file with passed id was not added, or already uploaded or cancelled');
        }

        var fileName = this.getName(id);

        var iframe = this._createIframe(id);
        var form = this._createForm(iframe, params);
        form.appendChild(input);

        var self = this;
        this._attachLoadEvent(iframe, function(){
            self.log('iframe loaded');

            var response = self._getIframeContentJSON(iframe);

            self._options.onComplete(id, fileName, response);
            self._dequeue(id);

            delete self._inputs[id];
            setTimeout(function(){
                imm.remove(iframe);
            }, 1);
        });

        form.submit();
        imm.remove(form);

        return id;
    },
    _attachLoadEvent: function(iframe, callback){
        imm.attach(iframe, 'load', function(){
            if (!iframe.parentNode){
                return;
            }

            if (iframe.contentDocument &&
                iframe.contentDocument.body &&
                iframe.contentDocument.body.innerHTML == 'false'){
                return;
            }

            callback();
        });
    },
    _getIframeContentJSON: function(iframe){

        var doc = iframe.contentDocument ? iframe.contentDocument: iframe.contentWindow.document,
            response;

        this.log("converting iframe's innerHTML to JSON");
        this.log('innerHTML = ' + doc.body.innerHTML);

        try {
            response = eval('(' + doc.body.innerHTML + ')');
        } catch(err){
            response = {};
        }

        return response;
    },
    _createIframe: function(id){

        var iframe = imm.toElement('<iframe src="javascript:false;" name="' + id + '" />');

        iframe.setAttribute('id', id);

        iframe.style.display = 'none';
        document.body.appendChild(iframe);

        return iframe;
    },
    _createForm: function(iframe, params){

        var form = imm.toElement('<form method="post" enctype="multipart/form-data"></form>');

        var queryString = imm.obj2url(params, this._options.action);

        form.setAttribute('action', queryString);
        form.setAttribute('target', iframe.name);
        form.style.display = 'none';
        document.body.appendChild(form);

        return form;
    }
});


imm.UploadHandlerXhr = function(o){
    imm.UploadHandlerAbstract.apply(this, arguments);

    this._files = [];
    this._xhrs = [];
    this._loaded = [];
};

// static method
imm.UploadHandlerXhr.isSupported = function(){
    var input = document.createElement('input');
    input.type = 'file';

    return (
        'multiple' in input &&
        typeof File != 'undefined' &&
        typeof (new XMLHttpRequest()).upload != 'undefined' );
};

imm.extend(imm.UploadHandlerXhr.prototype, imm.UploadHandlerAbstract.prototype)

imm.extend(imm.UploadHandlerXhr.prototype, {
    add: function(file){
        if (!(file instanceof File)){
            throw new Error('Passed obj in not a File (in imm.UploadHandlerXhr)');
        }

        return this._files.push(file) - 1;
    },
    getName: function(id){
        var file = this._files[id];
        // fix missing name in Safari 4
        return file.fileName != null ? file.fileName : file.name;
    },
    getSize: function(id){
        var file = this._files[id];
        return file.fileSize != null ? file.fileSize : file.size;
    },
    getLoaded: function(id){
        return this._loaded[id] || 0;
    },
    _upload: function(id, params){
        var file = this._files[id],
            name = this.getName(id),
            size = this.getSize(id);

        this._loaded[id] = 0;

        var xhr = this._xhrs[id] = new XMLHttpRequest();
        var self = this;

        xhr.upload.onprogress = function(e){
            if (e.lengthComputable){
                self._loaded[id] = e.loaded;
                self._options.onProgress(id, name, e.loaded, e.total);
            }
        };

        xhr.onreadystatechange = function(){
            if (xhr.readyState == 4){
                self._onComplete(id, xhr);
            }
        };

        // build query string
        params = params || {};
        params['immfile'] = name;
        var queryString = imm.obj2url(params, this._options.action);

        xhr.open('POST', queryString, true);
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        xhr.setRequestHeader('X-File-Name', encodeURIComponent(name));
        xhr.setRequestHeader('Content-Type', 'application/octet-stream');
        xhr.send(file);
    },
    _onComplete: function(id, xhr){
        // the request was aborted/cancelled
        if (!this._files[id]) return;

        var name = this.getName(id);
        var size = this.getSize(id);

        this._options.onProgress(id, name, size, size);

        if (xhr.status == 200){
            this.log('xhr - server response received');
            this.log('responseText = ' + xhr.responseText);

            var response;

            try {
                response = eval('(' + xhr.responseText + ')');
            } catch(err){
                response = {};
            }

            this._options.onComplete(id, name, response);

        } else {
            this._options.onComplete(id, name, {});
        }

        this._files[id] = null;
        this._xhrs[id] = null;
        this._dequeue(id);
    },
    _cancel: function(id){
        this._options.onCancel(id, this.getName(id));

        this._files[id] = null;

        if (this._xhrs[id]){
            this._xhrs[id].abort();
            this._xhrs[id] = null;
        }
    }
});




//collection_edit_popup
function collection_edit_popup(opt_mode, load_to_div_id, asset_type, asset_type_id, circle_id, user) {

    if ($('#asset_manager_frame').length >= 1)
    {
        $('#asset_manager_frame').remove();
    }

    var load_url = 'js/s101_admin/asset_manager/index.php?mode='+opt_mode+
                    '&asset_type='+asset_type+
                    '&asset_type_id='+asset_type_id+
                    '&circle_id='+circle_id+
                    '&user='+user;


    $('#'+load_to_div_id).load(load_url, function() {

        $('#asset_manager_frame').fadeIn(300);
    });
}



function collection_edit_popup_loaded() {

    $('#asset_manager_frame_cover').fadeOut(600);
    $('#asset_manager_iframe').fadeIn(600, function() {

        $('#asset_manager_frame_close').fadeIn(600);
    });
}


function collection_edit_popup_hide() {

    $('#asset_manager_frame').fadeOut(300, function() {

        $('#asset_manager_frame').remove();
    });
}


//networks
function choose_network(post_type) {

	var network_user = document.getElementById('network_user').value;
	var selected_networks = document.getElementById('selected_networks').value;

	var wind_url =   sn_script_path+'choose_network.php' +
					'?site_id='+network_user +
					'&post_type='+post_type +
					'&selected_networks='+selected_networks;


	var wind_params =   'width=580' +
                        ',height=610' +
                        ',left=100' +
                        ',top=100' +
                        ',screenX=100' +
                        ',screenY=100' +
                        ',menubar=0' +
                        ',scrollbars=1' +
                        ',status=0' +
                        ',toolbar=0' +
                        ',titlebar=0';

    var user_network_wind = window.open(wind_url, ' choose_network', wind_params);
}


//networks
function share_item_window(obj_id, site_id, force_networks) {

	var network_user = $('#g_user').val();

	var wind_url =   sn_script_path+'share_item.php' +
					'?site_id='+site_id +
					'&obj_id='+obj_id +
					'&user='+network_user +
					'&selected_networks=' +
					'&force='+force_networks;


	var wind_params =   'width=660' +
                        ',height=800' +
                        ',left=100' +
                        ',top=100' +
                        ',screenX=100' +
                        ',screenY=100' +
                        ',menubar=0' +
                        ',scrollbars=1' +
                        ',status=0' +
                        ',toolbar=0' +
                        ',titlebar=0';

    var user_network_wind = window.open(wind_url, 'share_item_on', wind_params);
}


function link_to_network(network) {

    var wind_width;
    var wind_height;
    var sn_script_path = '/js/s101_admin/social_networks/';

	if (network == 'twitter')
	{
		wind_width = 600;
    	wind_height = 400;
	}
	else if (network == 'facebook')
	{
		wind_width = 1000;
    	wind_height = 600;
	}
	else if (network == 'tumblr')
	{
		wind_width = 950;
    	wind_height = 600;
	}
	else if (network == 'google_plus')
	{
		wind_width = 650;
    	wind_height = 500;
	}
	else
	{
		wind_width = 900;
    	wind_height = 600;
	}

    var left_pos = parseInt(screen.availWidth / 2 - wind_width / 2);
    var top_pos = parseInt(screen.availHeight / 2 - wind_height / 2) - 200;
    var wind_params =   'width='+wind_width +
                        ',height='+wind_height +
                        ',left='+left_pos +
                        ',top='+top_pos +
                        ',screenX='+left_pos +
                        ',screenY='+top_pos +
                        ',menubar=0' +
                        ',scrollbars=0' +
                        ',status=0' +
                        ',toolbar=0' +
                        ',titlebar=0';

    var network_window = window.open(sn_script_path+'networks/index.php?q='+network, 'network_window_q', wind_params);
}


function activate_network_icon(network) {

    var cur_icon_class = document.getElementById(network+'_icon_row').className;
    var cur_selected_networks = document.getElementById('selected_networks').value;
    var new_selected_networks;

    if (cur_icon_class == 'send_to_networks_do')
    {
        new_selected_networks = cur_selected_networks.replace('_none_', '').replace(network+'|', '');
        $('#'+network+'_icon_row').attr('class', 'send_to_networks_dont');
    }
    else
    {
        new_selected_networks = cur_selected_networks.replace('_none_', '').replace(network+'|', '')+network+'|';
        $('#'+network+'_icon_row').attr('class', 'send_to_networks_do');
    }

    document.getElementById('selected_networks').value=new_selected_networks;

    if (new_selected_networks.length == 0)
	{
    	document.getElementById('selected_networks').value = '_none_';
    	document.getElementById('send_to_networks_do_box').checked=false;
    	document.getElementById('send_to_networks_do_box_div').className='send_to_networks_checked_not';
    }
    else
    {
    	document.getElementById('send_to_networks_do_box').checked=true;
    	document.getElementById('send_to_networks_do_box_div').className='send_to_networks_checked';
    }
}


function refresh_networks() {

	document.getElementById('send_to_networks_do_box').click();

	var send_to_networks_do_box = document.getElementById('send_to_networks_do_box');

	if (send_to_networks_do_box.checked == true)
	{
		if (document.getElementById('selected_networks').value == '_none_')
		{
			document.getElementById('selected_networks').value = '';
		}

		document.getElementById('send_to_networks_do_box_div').className = 'send_to_networks_checked';
	}
	else
	{
	    document.getElementById('send_to_networks_do_box_div').className = 'send_to_networks_checked_not';
	}
}

function loading_div(div_id) {

    document.getElementById(div_id).innerHTML='<img src="/js/s101_admin/images/update_Progress.gif" alt="" style="position:absolte;z-index:20;height:60px;" />';
}
