var timeout_id;
var counter;
var progress_timeout_id;
$(document).ready(function(){
        $('#log_form .check_all').click(function(){
                if($(this).hasClass('checked')){
                        $('#log_form input[type=checkbox]').removeAttr('checked');
                        $(this).removeClass('checked');
                } else {
                        $('#log_form input[type=checkbox]').attr('checked',true);
                        $(this).addClass('checked');
                }
        });
        $('#log_form .submit_form').click(function(){
            var items_selected = $('#log_form input[type=checkbox]:checkbox:checked').length;
            if(items_selected == 0){
                    alert('Please select items first.');
                    return false;
            }
            else
            {
                var action_up = $('#action_up').val();
                var action_down = $('#action_down').val();
                if (action_up == '' && action_down == '')
                {
                    alert('Please select what to do with selected items.');
                    return false;
                }
            }
         
        });
	if($('#db_file_update').get(0)){
		var error = '';
		$('#db_file_update').submit(function(){
			var checked_cols = $('input.display_columns[checked]').length;
			var drag_scan = $('#dragged_SCANBOX').get(0);
			if(!drag_scan){
				error += "Please drag scanbox to one of columns from your lookup file\n";
			} 
			if(checked_cols == 0){
				error += "You should check columns that you want to display in result file\n";
			} else if (checked_cols == 1 && !error){
				var col = $('input.display_columns[checked]').get(0);
				if($(col).attr('name') == 'display_columns['+$('#dragged_SCANBOX').val()+']'){
					error += "You should check columns that you want to display in result file except mapping column\n";
				}
			}
			if(error){
				alert(error);
				error = '';
				return false;
			}
			return true;
		})
	}
    if($('#convet_db_file').get(0)){
		$('#convet_db_file').submit(function(){
                    var descriptionMap = $('#dragged_DescriptionMap').get(0);
                    if (descriptionMap ){
                        var itemMap = $('#dragged_ItemIDMap').get(0);
                        var upcMap = $('#dragged_UPCMap').get(0);
                        if (!itemMap && !upcMap){
                            alert('You should map ItemID or UPC column. You can also upload the file without using FTS.');
                            return false;
                        }
                    }

            return true;
		})
	}  
	
	if($('#scannersn_tr').get(0)) {
		$('#group_chk').click(function(){
			if($(this).attr('checked')) {
				$('#scannersn_tr').fadeIn(300);
			} else {
				$('#scannersn_tr').fadeOut(300);
			}
		})
	}	
	if($('#add_drag').get(0)){
		$('#add_drag').unbind('click');
		$('#add_drag').click(function(){
			var box_count = $('#dropContent div.dragableBox').length;
			var box_val = $.trim($('#add_to_drag').val());
			var box_name = $.trim($('#add_to_drag option[value="'+box_val+'"]').html());
			if(box_name){
				$('<div class="dragableBox" id="'+box_val+'">'+box_name+'</div>').appendTo('#dropContent');
				$('#add_to_drag option[value="'+box_val+'"]').remove();
				dragDropObj.addSource(box_val,true);
				dragDropObj.init();
			}
			
		})
	}
	
	if($('.ui-sort-container').get(0)){
		$(".ui-sort-container").sortable({
		        connectWith: '.ui-sort-container',
		        items: 'div.dragableBoxRight'
		    });
	}

     if($('#file_type').get(0)){
        $('#file_type').change(function(){
            var jThis = $(this);
            var selectValue = jThis.val();
            if (selectValue == 1){
               $('#without_fts').removeAttr('checked');
               return;
            }else if (selectValue == 2){
               $('#without_fts').attr('checked','checked');
            }
        })
    }

    if($('#assign_cust_action_select').get(0)){
        $('#assign_cust_action_select').change(function(){
            var jThis = $(this);
            var selectValue = jThis.val();
            if (selectValue == 0){
               $('#setfilenamerow').attr('style','display:none;');
               $('#saverow').attr('style','display:none;');
               $('#uploadfilerow').attr('style','display:none;');
               $('#submitrow').attr('style','display:none;');
               return;
            }else if (selectValue == 1){
               $('#setfilenamerow').attr('style','display:table-row;');
               $('#saverow').attr('style','display:table-row;');
               $('#uploadfilerow').attr('style','display:none;');
               $('#submitrow').attr('style','display:none;');
            }else if (selectValue == 2){
               $('#setfilenamerow').attr('style','display:none;');
               $('#saverow').attr('style','display:none;');
               $('#uploadfilerow').attr('style','display:table-row;');
               $('#submitrow').attr('style','display:table-row;');
            }            
        })
    }
	
	if($('#delivery_format_select').get(0)){
		$('#delivery_format_select').change(function(){
			if($(this).val() == 'HTML'){
				$('tr.html_parts').attr('style','display:table-row;');
				$('tr.xls_parts').attr('style','display:none;');
				$('tr.csv_parts').attr('style','display:none;');
			} else if($(this).val() == 'XLS') {
				$('tr.html_parts').attr('style','display:none;');
				$('tr.xls_parts').attr('style','display:table-row;');
				$('tr.csv_parts').attr('style','display:none;');
			} else if ($(this).val() == 'CSV'){
			    $('tr.html_parts').attr('style','display:none;');
			    $('tr.xls_parts').attr('style','display:none;');
			    $('tr.csv_parts').attr('style','display:table-row;');
                $('#csv_col_sep').attr("disabled", "");
			} else if ($(this).val() == 'TXT'){
			    $('tr.html_parts').attr('style','display:none;');
			    $('tr.xls_parts').attr('style','display:none;');
			    $('tr.csv_parts').attr('style','display:table-row;');
			    /*
			     $('#csv_col_sep').val("2");
			     $('#csv_col_sep').attr("disabled", "disabled");
			     */
			}
		})
	}
	if($('#timer').get(0)){
		close_window();
	}
	if($('a.file_selected').get(0)){
	    $('a.file_selected').click(function(){
	        return confirm('This file is currently used to Perform List Lookup. If you remove this file Perform List Lookup will be disabled. Are you sure you want to do this?');
	    })
	}
	
	if($('a.process').get(0)){
	    $('a.process').click(function(){
	        $.post(
                $(this).attr('href'),
                {'action':'process',
                 'file_id':$(this).attr('rel')},
                function (resp) {
                    if(resp.error){
                        alert(resp.msg);
                        clearTimeout(timeout_id);
                    }
                    window.location.href=window.location.href;
                },
                'json'
	        )
	        $('div.progress').slideDown(200);
	        setTimeout("show_geo_status('"+$(this).attr('href')+"',"+$(this).attr('rel')+")",2000);
	        return false;
	    })
	}

        if($('#ftp_update_data').get(0)){
	    $('#ftp_update_data').click(function(){
               $.post(
                site_url+'db.php',
                {'action':'generate_id'},
                function (resp) {
                    //alert(resp);
                    $('#progress_id').val(resp);
                }
	        );

                $('div.progressBar')
                    .html('')
                    .width(0);
               $('#percents').html('0%');
               $('#progress_info').html('(initializing)');
                var container = $('div.results_errors');
                container.html('');
                var id = $('#progress_id').val();
                $.post(
                site_url+'db.php',
                {'action':'process',
                 'id':id},
                function (resp) {
                     if(resp.error){
                        alert(resp.msg);
                    }else{
                       // alert(resp.errors);
                        if (resp.errors.length > 0){
                            var container = $('div.results_errors');                
                            for(i=0;i<resp.errors.length;i++){
                                container.append(resp.errors[i]);
                                container.append('<br/>');
                            }
                            container.append('<br/>');
                            container.slideDown(200);
                        }
                    }
                    //window.location.href=window.location.href;
                },
                'json'
	        );

	        $('div.progress').slideDown(200);
                $('#ftp_update_data').hide();
	        setTimeout("show_ftp_download_status('', '"+id+"', 'get_ftp_download_status')",500);
	        return false;
	    })
	}     

        jQuery("#display_sn").click(function(){       
        
            if (jQuery("#display_sn").is(":checked"))
            {
                jQuery("#append_sn_to_first_row_control_holder").fadeIn(300);
            }
            else
            {
                jQuery("#append_sn_to_first_row_control_holder").fadeOut(300);
            }
          });
        jQuery("#combine_quantities").click(function(){
           if (jQuery("#combine_quantities").is(":checked"))
            {
                jQuery(".combineQuantities").fadeIn(300);
            }
            else
            {
                jQuery(".combineQuantities").fadeOut(300);
            }
        });

        jQuery("#submit").click(function(){
            if (jQuery("#combine_quantities").is(":checked"))
                {                 
                    var scan_column_number = jQuery("#scan_column_number").val();
                    if (!isInteger(scan_column_number) || !isPositiveInteger(scan_column_number)){
                       alert("Please enter a valid scan column index!");
                       jQuery("#scan_column_number").focus();
                       return false;
                    }

                    var quantity_column_number = jQuery("#quantity_column_number").val();
                    if (!isInteger(quantity_column_number) || !isPositiveInteger(quantity_column_number)){
                       alert("Please enter a valid quantity column index!");
                       jQuery("#quantity_column_number").focus();
                       return false;
                    }
                    
                    if (quantity_column_number == scan_column_number){
                        alert("Quantity column index and scan column index must be different!");
                       return false;
                    }
                }
                return true;
        });
       
});

function show_geo_status(url,file_id){
    $.post(
        site_url+"get_status.php",
        {'action':'get_status',
         'file_id':file_id},
        function (resp) {
            if(resp!='error'){
                if(resp.processed>0){
	                var processed = resp.processed;
	                var total_rows = resp.num_rows;
	                var percent_complete = Math.ceil((resp.processed/resp.num_rows)*100);
	                var progress_length = percent_complete*3;
	                $('div.progressBar').width(progress_length);
	                $('#percents').html(percent_complete+'%');
	                $('#progress_info').html(processed+' from '+total_rows);
	                if(total_rows == processed){
	                    clearTimeout(timeout_id);
	                    $('div.progressBar').html('Updating file...');
	                }
                }
            }
        },
        'json'
    )
    counter++;
    timeout_id = setTimeout("show_geo_status('"+url+"',"+file_id+")",2000);
}

function show_ftp_download_status(url, id, action){
   
    $.post(
        site_url+"get_status.php",
        {'action':action,
         'id':id},
        function (resp) {
            if(resp!='error'){
                if(resp.processed>0){
	               var processed = resp.processed;
	                var total_rows = resp.num_rows;
	                var percent_complete = Math.ceil((resp.processed/resp.num_rows)*100);
	                var progress_length = percent_complete*3;
	                $('div.progressBar').width(progress_length);
	                $('#percents').html(percent_complete+'%');
	                $('#progress_info').html(processed+' from '+total_rows);
	                if(total_rows == processed){
	                    clearTimeout(timeout_id);
	                    $('div.progressBar').html('Download is completed!');
                            $('#ftp_update_data').show();
	                }
                }
            }else{
                clearTimeout(timeout_id);
            }
        },
        'json'
    )
    timeout_id = setTimeout("show_ftp_download_status('"+url+"', '"+id+"', 'get_ftp_download_status')",500);
}