/**
 * @author Johan
 */
var _NORMAL_UPLOAD_ = "NORMAL_UPLOAD";
var _UPDATE_UPLOAD_ = "UPDATE_UPLOAD";
var tuRegex = /^[a-z0-9_.\-]+$/i;

function timedRefresh(timeoutPeriod){
    setTimeout("location.reload(true);", timeoutPeriod);
}

function disableFile(){
    jQuery("#file").attr("disabled", "disabled");
}

function enableFile(){
    jQuery("#file").removeAttr("disabled");
}

function showUpdateThemeModes(){
	jQuery("#submit-action").val(_UPDATE_UPLOAD_);
	var data = {
        request_action: "view-theme-modes"
    };
    jQuery.post(TuAjax.tuThemeCheckerActionUrl, data, function(response){
		jQuery("#tu-loading").hide();
		jQuery('input[type="file"]').attr("disabled", "disabled");
        jQuery("#div-msg").html("The name you have selected is already in the system.  Please rename your theme upload");
        jQuery("#div-msg").attr("class", "error-msg");		
        jQuery("#update-modes").html(response);
        jQuery("#update-modes").attr("class", "div-update-modes-show");
    });
}

function updateMode(){
    var mode = jQuery("input[name='update-mode']:checked").val();
    if (mode == 1) {
        jQuery("#div-update-theme-title-text").attr("class", "div-update-theme-title");
    }
    else if (mode == 2 || mode == 3) {
        jQuery("#div-update-theme-title-text").attr("class", "div-update-theme-title-show");
	}
}

function tuCheckFileNameExistence(action, mode, theme_name){
	if (jQuery.trim(theme_name) == "") {
		jQuery("#tu-loading").hide();
		return;
	}
	if (action == _UPDATE_UPLOAD_ && (!tuRegex.test(theme_name)) ) {
		jQuery("#tu-loading").hide();
		alert("Theme name should not consist wild characters nor spaces.");
		return;
	}
	
    var data = {
        request_action: "theme-check",
        theme_name: theme_name
    };
    jQuery.post(TuAjax.tuThemeCheckerActionUrl, data, function(response){
        if (response === "true") {		
			showUpdateThemeModes();
        } else {
        	tuAjaxFileUpload(action, mode, theme_name);
        }
    });
}

function resetEntities() {
	jQuery("#upload-theme").removeAttr("disabled");
	jQuery("#tu-loading").hide();
    jQuery("#submit-action").val(_NORMAL_UPLOAD_);
    jQuery("#update-modes").html("");
    jQuery("#update-modes").attr("class", "div-update-modes");
}

function tuAjaxFileUpload(request_action, update_mode, theme_name){
	jQuery("#upload-theme").attr("disabled", "disabled");
    jQuery.ajaxFileUpload({
        url: TuAjax.tuAjaxActionUrl,
        secureuri: false,
        fileElementId: 'file',
        dataType: 'json',
        data: {update_mode: update_mode, theme_name: theme_name, request_action: request_action},
        success: function(data, status) {
        	var json = eval(data);
        	if (typeof(json.data) == "string") {
        		jQuery("#div-msg").attr("class", "success-msg");
        		jQuery("#div-msg").html(json.data);
        	} else if (typeof(json.data) == "object") {
	        	var str = '';
	        	for (var i=0; i < json.data.length; i++) {
	        		str += json.data[i] + "<br/>";
	        	}
	        	jQuery("#div-msg").attr("class", "error-msg");
	        	jQuery("#div-msg").html(str);
        	}
			resetEntities();
        },
        error: function(data, status, e){
			resetEntities();
            //alert("Unexpected error occured. Try again.");
        }
    });
	
    
}

function updateModeBulk(key) {
	jQuery("#"+key+"-td-status").removeAttr("class");
	jQuery("#"+key+"-td-status").html("");
    var mode = jQuery("input[name='"+key+"-upload-mode']:checked").val();
    if (mode == 1) {
        jQuery("#"+key+"-theme-name-update-div").html("");
    }else if (mode == 2 || mode == 3) {
		jQuery("#"+key+"-theme-name-update-div")
			.html('<input type="text" class="tu-theme-name-update-text" name="'+key+'-theme-name-update" id="'+key+'-theme-name-update" size="40" maxlength="50" />');
	}
}
function checkThemeName(key) {
	var themeName = jQuery("#"+key+"-theme-name-update").val();
	var data = {
		request_action: "theme-check",
		theme_name: themeName
	};
	
	jQuery("#"+key+"-td-status")
	.html("")
	.removeAttr("class");
    jQuery.post(TuAjax.tuThemeCheckerActionUrl, data, function(response){
    	if (response === "true") {
    		jQuery("#"+key+"-td-status")
    		.attr("class", "exists")
    		.html("exists");
    	}
    });
    
}

function processBulkUploadData(email, themeNames) {
	var themesList = new Array();
	var themeExist = false;
	for (var key = 0; key < themeNames.length; key++) {
		var themeData = new Object();
		var themeName = jQuery(themeNames[key]).val();
		var mode = jQuery("input[name='"+key+"-upload-mode']:checked").val();
		if (mode == 2 || mode == 3) {
			themeData['theme_name_update'] = jQuery("#"+key+"-theme-name-update").val();
		}
		themeData['file_name'] = themeName+".zip";
		themeData['upload_mode'] = mode;
		themesList[key] = themeData; 
	}
	
	var data = {
        request_action: "bulk-upload-process",
		email: email,
        themes_list: themesList
    };
	
	jQuery.post(TuAjax.tuAjaxActionUrl, data, function(response){
		jQuery("#tu-processing").hide();
		jQuery("#tu-div-upload-result").html(response);
		timedRefresh(2000);
	});
}

function tu_highlightOn(row) {
	jQuery("#tbl-bulk-upload-themes input#"+row+"-theme-name-update").attr("style", "background-color: #D7E7FF;");
	jQuery("#tbl-bulk-upload-themes input#"+row+"-theme-name").attr("style", "background-color: #D7E7FF;");
}

function tu_highlightOff(row) {
	jQuery("#tbl-bulk-upload-themes input#"+row+"-theme-name-update").removeAttr("style");
	jQuery("#tbl-bulk-upload-themes input#"+row+"-theme-name").removeAttr("style");
}

function loadThemesBulkUploadView() {
	var data = {request_action: "load-bulk-upload-view", 'default': '1'};
	jQuery.post(TuAjax.tuAjaxActionUrl, data, function(response){
		jQuery("#tu-div-themes-list").html(response);
		var themeNames = jQuery("#tbl-bulk-upload-themes input.tu-file-name-text");
		if (themeNames.length > 0) {
			jQuery("#tu-btn-check-filenames").show();
		}
	});
}

jQuery(document).ready(function() {
	
    jQuery("input#tu-upload-theme").click(function() {
		jQuery("#tu-loading").show();
        var submitAction = jQuery("#submit-action").val();
        switch (submitAction) {
            case _NORMAL_UPLOAD_:
                var filename = jQuery('input[type="file"]').val();
                tuCheckFileNameExistence(_NORMAL_UPLOAD_, 0, filename);
                break;
            case _UPDATE_UPLOAD_:
                jQuery('input[type="file"]').removeAttr("disabled", "disabled");
                var mode = jQuery("input[name='update-mode']:checked").val();
                if (mode == 1) {
                	tuAjaxFileUpload(_UPDATE_UPLOAD_, mode, "");
                } else if (mode == 2 || mode == 3) {
                    var theme_name = jQuery("#tu-text-update-theme-title").val();
                    tuCheckFileNameExistence(_UPDATE_UPLOAD_, mode, theme_name);
                }
                break;
        }
    });
	
	jQuery("input#tu-btn-check-filenames").click(function(){
		jQuery("#tu-checking").show();
		var data = {request_action: "check-zipnames-existence"};
		jQuery.post(TuAjax.tuAjaxActionUrl,data , function(response){
		 	jQuery("#tu-checking").hide();
	        jQuery("#tu-div-themes-list").html("");
			jQuery("#tu-div-themes-list").html(response);
			jQuery("#tu-btn-process-data").show();
			jQuery("#div-bulk-upload-instructions").show();
	   });
	});
	
	jQuery("input#tu-btn-process-data").click(function() {
		jQuery("#tu-processing").show();
		var emailRegEx = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
		var email = jQuery.trim(jQuery("input#tu-report-email").val());
		if (email == "" || !emailRegEx.test(email)) {
			jQuery("#tu-processing").hide();
			alert("Please enter a valid email address.");
			return;
		}
		jQuery("#tbl-bulk-upload-themes td.exists").html("");
		var themeNameUpdates = jQuery("#tbl-bulk-upload-themes input.tu-theme-name-update-text");
		var themeNames = jQuery("#tbl-bulk-upload-themes input.tu-file-name-text");
		if (themeNameUpdates.length == 0) {
			processBulkUploadData(email, themeNames);
		} else {
			var themesList = new Object();
			var hasDup = false;
			var themeNameExists = false;
			
			loop1:
			for (var i = 0; i < themeNameUpdates.length; i++) {
				var updKey = jQuery(themeNameUpdates[i]).attr('id').split('-')[0];
				var themeName = jQuery("#"+updKey+"-theme-name").val();
				var themeNameUpdate = jQuery(themeNameUpdates[i]).val();
				
				if (jQuery.trim(themeNameUpdate) == "") {
					jQuery("#tu-processing").hide();
					alert("Please fill all textboxes.");
					return;
				}
				//checks if theme name update is the same with its current theme name.
				if (themeNameUpdate.toLowerCase() === themeName.toLowerCase()) {
					jQuery("#tu-processing").hide();
					alert(themeNameUpdate + " should not be the same with the current\ntheme name when mode 2 or 3 is selected.");
					return;
				} 
				//checks for wild characters
				if (!tuRegex.test(themeNameUpdate)) {
					jQuery("#tu-processing").hide();
					alert(themeNameUpdate + " should not consist wild characters nor spaces.");
					return;
				}
				
				loop2:
				//checks theme name updates agains each of theme name
				for (var h = 0; h < themeNames.length; h++) {
					if (themeNameUpdate.toLowerCase() === jQuery(themeNames[h]).val().toLowerCase()) {
						hasDup = true;
						break loop1;	
					}
				}
				//checks theme name updates amongs them.
				loop3:
				for (var j = 0; j < themeNameUpdates.length; j++) {
					//exclude self from checking duplicate and check the rest of elements.
					if (updKey+"-theme-name-update" != jQuery(themeNameUpdates[j]).attr('id') && 
						jQuery(themeNameUpdates[j]).val().toLowerCase() === themeNameUpdate.toLowerCase()) {
						hasDup = true;
						break loop1;
					}
				}
				themesList[updKey] = themeNameUpdate;
			}
			if (hasDup) {
				jQuery("#tu-processing").hide();
				alert("Theme names update should not have duplicates\nnor theme names should not be the same with any of the theme name updates.");
				return;
			}
			var data = {
				themes_list: themesList, request_action: "themes-check"
			};
			jQuery.post(TuAjax.tuThemeCheckerActionUrl, data, function(response){
				var json = eval(response);
				var str = "";
				for(var index in json.data) {
					if (json.data[index] === "true") {
						themeNameExists = true;
						jQuery("#" + index + "-td-status").attr("class", "exists");
						jQuery("#" + index + "-td-status").html("exists");
					} else {
						jQuery("#" + index + "-td-status").removeAttr("class");
						jQuery("#" + index + "-td-status").html("");
					}
				}
				if (themeNameExists) {
					jQuery("#tu-processing").hide();
					alert("Some theme name(s) update are/is already in the system. Not applicable when mode 2 or 3 is selected.");
					return;
				}
				processBulkUploadData(email, themeNames);
			}, 'json');
		}
	});
	

});
 
