﻿var dataOrigin = "";
function getChannels(datatype, id, obj, level) {
    $.getJSON("/Canais/List/" + id, null, function(data) {
        var mDiv = "<div class=\"submenus\" id=\"subMenus" + id + "\">";
        var moreCss = level + 1;
        for (iCount = 0; iCount < data.length; iCount++) {
            if (data[iCount].childcount > 0)
                mDiv += '<li><a onclick="getChannels(\'' + data[iCount].datatype + '\', \'' + data[iCount].id + '\', this, ' + moreCss + ');" class="more' + (level + 1) + '" href="#more">+</<a> <a class="link" href="javascript:void(0);" onclick="loadPage(\'/' + data[iCount].channelName + '/Index/' + data[iCount].id + '\')" >' + data[iCount].name + '</a></li>';
            else
                mDiv += '<li><a href="javascript:void(0);" class="more' + moreCss + '">-</<a> <a class="link" href="javascript:void(0);" onclick="loadPage(\'/' + data[iCount].channelName + '/Index/' + data[iCount].id + '\')" >' + data[iCount].name + '</a></li>';
        }
        mDiv += "</div>";
        $(obj).parent().after(mDiv);
    });
    $(obj).removeAttr("onclick");
    $(obj).click(function() {
        $("#subMenus" + id).toggle();
    });
}

function loadPage(uri) {
    $("#main").load(uri);
}

function saveFeed() {
    var isOk2Go = true;
    if (!checkForInvalidValue($("#title"))) isOk2Go = false;
    if (!checkForInvalidValue($("#url"))) isOk2Go = false;
    if (isOk2Go) {
        doPostBack("/Feeds/TestFeed/", "url=" + $("#url").val(), function(data) {
            if (data) {
                doPostBack("/Feeds/Add/" + $("#id").val(), $("#frmFeeds").serialize())
            } else {
                $("#errMsg").html(langOptions.FeedError);
            }
        });
    }
}

function saveFileItem(state) {
    if (state == 1) $("#status").val(state);
    selectAll("Categories");
    document.getElementById("itemForm").submit();
    var isOk2Go = true;
    if (!checkForInvalidValue($("#title"))) isOk2Go = false;
    if (!checkForInvalidValue($("#tags"))) isOk2Go = false;
    if ($("#id").length == 0) {
        if ($("#fileName").val() == "") isOk2Go = false;
    }
    if (isOk2Go) {
        $(".submit").val("Uploading and converting file if necessary, please wait...");
    }
}

function saveItem(state) {
    var isOk2Go = true;
    var imgArray = "";
    var linkArray = "";
    var catArray = "";
    var catAreas = "";
    var fileArray = "";
    
    if (!checkForInvalidValue($("#title"))) isOk2Go = false;
    if (!checkForInvalidValue($("#iniDate"))) isOk2Go = false;
    if (!checkForInvalidValue($("#tags"))) isOk2Go = false;

    $("#images option").each(function() {
        imgArray += $(this).val() + ",";
    });
    $("#links option").each(function() {
        linkArray += $(this).val() + ",";
    });
    $("#Categories option").each(function() {
        catArray += $(this).val() + ",";
    });
    $("#files option").each(function() {
        fileArray += $(this).val() + ",";
    });
    
    if (imgArray != "") imgArray = imgArray.substr(0, imgArray.length - 1);
    if (linkArray != "") linkArray = linkArray.substr(0, linkArray.length - 1);
    if (catArray != "") catArray = catArray.substr(0, catArray.length - 1);
    if (fileArray != "") fileArray = fileArray.substr(0, fileArray.length - 1);
    
    if (!channelID) channelID = 0;
    if ($("#Areas").length > 0) {
        if ($("#Areas option").length > 0) {
            $("#Areas option:selected").each(function() {
                catAreas += $(this).val() + ",";
            });
            if (catAreas != "") catAreas = catAreas.substr(0, catAreas.length - 1);
        } else {
            catAreas = $("#Areas").val();
        }
    }
    
    var form = $("#itemForm");
    var formData = "title=" + $("#title").val() + "&lead=" + $("#lead").val() + "&text=" + $("#text").val() +
                "&author=" + $("#author").val() + "&tags=" + $("#tags").val() + "&html=" + escape(CKEDITOR.instances.html.getData()) +
                "&iniDate=" + $("#iniDate").val() + "&endDate=" + $("#endDate").val() + "&images=" + imgArray + "&links=" + linkArray +
                "&areaid=" + channelID + "&categories=" + catArray + "&GreenFactor=" + $("#GreenFactor").val() + "&areas=" + catAreas + "&fs=" + fileArray;
        
    if ($("#id").length > 0) formData += "&id=" + $("#id").val();
    if (isOk2Go) {
        var action = state == 1 ? "Publish" : "Add";
        var msg = new errorDetail();
        doPostBack("/Articles/" + action, formData);
    } else {
        setErrMsg("<b>Campos inválidos! Verifique os os valores<b>");        
    }
}

function setErrMsg(msg) {
    $("#errMsg").html(msg);
}

function clearForm() {
    $("#images option").remove();
    $("#links option").remove();
    $("#Categories option").remove();
    $("textarea").val("");
    $("input:text").val("");
    if (CKEDITOR.instances['html']) {
        CKEDITOR.remove(CKEDITOR.instances['html']);
    }
    $("#filtro").hide();
}

function checkForInvalidValue(obj) {
    var myReg = /^\s+|\s+$/i;

    try{
        var sVal = obj.val();
        sVal = sVal.replace(myReg, "");
        obj.val(sVal);
        if (obj.val() == "") {
            obj.animate({ backgroundColor: "#D0AFAE" });
            return false;
        } else {
            obj.animate({ backgroundColor: "#FFFFFF" });
        }
    }catch(e){
        return false;
    }
    return true;
}

function addOption(container, id, title, checked) {
    if (checked) {
        var optn = document.createElement("option");
        optn.text = title;
        optn.value = id;
        document.getElementById(container).options.add(optn);
        document.getElementById(container).options[document.getElementById(container).options.length-1].selected = true;
    } else {
        $("#" + container + " option").each(function() {
            if($(this).val()==id) $(this).remove();
        });
    }
}

function selectAll(container) {
    $("#" + container + " option").attr("selected", "selected");
}

function removeItems(container) {
    $('#' + container).children('option:selected').remove();
}

function orderItems(obj, movement){
    if ($("#" + obj + " option:selected").length == 1) {
        if (movement == "UP") {
            if ($("#" + obj + " option:selected").prev().length > 0) {
                var opt = $("#" + obj + " option:selected").prev();
                $("#" + obj + " option:selected").insertBefore(opt);
            }
        } else {
            if ($("#" + obj + " option:selected").next().length > 0) {
                var opt = $("#" + obj + " option:selected").next();
                $("#" + obj + " option:selected").insertAfter(opt);
            }
        }
    } else {
        alert("Please select 1 item!");
    }
}

function resizeWindow(w, h) {
    $("#fancy_outer").animate({ width: w, height: h }, 'fast');
    setTimeout('setView()', 500);    
}

function setView() {
    var pos = $.fn.fancybox.getViewport();
    $("#fancy_outer").animate({
        left: (($("#fancy_outer").width() + 36) > pos[0] ? pos[2] : pos[2] + Math.round((pos[0] - $("#fancy_outer").width() - 36) / 2)),
        top: (($("#fancy_outer").height() + 50) > pos[1] ? pos[3] : pos[3] + Math.round((pos[1] - $("#fancy_outer").height() - 90) / 2))
    }, 'fast');
}


function errorDetail(errType, errMsg, action) {
    this.errType = errType;
    this.errMsg = errMsg;
    this.action = action;
}

function addItemToList(text) {
    if ($("#tbList tbody tr").length == 0) {
        $("#tbList tbody").append(text);
    } else {
        $("#tbList tbody tr:first").before(text);
    }
}

function unPublish(id, obj) {
    if (confirm(langOptions.AreYourSureUnPublish)) {
        $.get("/Content/status/" + id, { action: "unpublish", db: dataOrigin, id: id }, function(data) {
            if (data) {
                $(obj).parent().prev().html("New");
                $(obj).html(langOptions.Publish);
                obj.setAttribute("onclick", "Publish(" + id + ", this);");
            } else {
                alert(langOptions.ChangeStateError);
            }
        })
    }
}

function Publish(id, obj) {
    if (confirm(langOptions.AreYouSurePublish)) {
        $.get("/Content/status/" + id, { action: "publish", db: dataOrigin, id: id }, function(data) {
            if (data) {
                $(obj).parent().prev().html("Publish");
                $(obj).html(langOptions.unPublish);
                obj.setAttribute("onclick", "unPublish(" + id + ", this);");
            } else {
                alert(langOptions.ChangeStateError);
            }
        })
    }
}

function deleteItem(id, obj) {
    if (confirm(langOptions.AreYouSureDelete)) {
        $.get("/Content/status/" + id, { action: "delete", db: dataOrigin, id: id }, function(data) {
            if (data) {
                $(obj).parent().parent().remove();
            } else {
                alert(langOptions.ChangeStateError);
            }
        })
    }
}

function filterComments(page) {
    var formData = $("#frmFilter").serialize();
    $.getJSON("/Comments/Filter/" + page, formData, function(data) {
        $(".paginas").html("");
        var html = "<strong>Páginas:</strong>";
        for (iCount = 0; iCount < data.itemsCount; iCount++) {
            var selected = data.pageNumber == iCount + 1 ? "class=\"selected\"" : "";
            html += "<a href=\"javascript:void(0);\" onclick=\"filterComments(" + (iCount + 1) + ");\"" + selected + ">" + (iCount + 1) + "</a>";
        }
        $(".paginas").html(html);

        html = "";
        $("#tbList tbody").html("");
        for (iCount = 0; iCount < data.items.length; iCount++) {
            item = data.items[iCount];
            html += "<tr><td title=\"" + item.user.replace('"', '\"') + "\"><a href=\"javascript:void(0);\" onclick=\"$('#filtro').load('/Comments/Edit/" + item.id + "', function(){$('#filtro').hide().show('fast');});\">" + item.user + "</a></td>";
            html += "<td>" + item.email + "</td>";
            html += "<td>" + item.article + "</td>";
            html += "<td>" + item.lead + "</td>";
            html += "<td>" + item.data + "</td>";
            html += "<td>" + item.status + "</td></tr>";
        }

        $("#tbList tbody").html(html);
    });
}

function saveComment(state, id) {
    var isOk2Go = true;
    var formData = $("#itemForm").serialize();
    formData += "&status=" + state;
    if (!checkForInvalidValue($("#title"))) isOk2Go = false;
    if (isOk2Go) {
        doPostBack("/Comments/Edit/" + id, formData);
    }
}

function setOption(action, key, value) {
    $.getJSON("/Options/" + action + "/" + key, "val=" + value, function(data) {
        if (data.type == 1) {
            eval(data.action);
        } else {
            alert(data.msg);
        }
    });
}

function setClickTree() {
    $(this).unbind("click", setClickTree);
    clicked = this;
    doPostBack("/Canais/List/" + $(this).attr("value"), "", expandTree);
}

function expandTree(data) {
    var myUL = "<ul class=\"expandable\">";
    for (iCount = 0; iCount < data.length; iCount++) {
        var css = "";
        var css = data[iCount].childcount > 0 ? "expandable" : "";
        myUL += "<li class=\"" + css + "\">";
        if (data[iCount].childcount > 0) {
            myUL += "<div class=\"hitarea expandable-hitarea\" value=\"" + data[iCount].id + "\"/>";
        }
        myUL += "<a class=\"link\" onclick=\"loadChannel('" + data[iCount].id + "');\">" + data[iCount].name + "</a></li>";
    }
    myUL += "</ul>";
    $(clicked).removeClass("hitarea expandable-hitarea").addClass("hitarea collapsable-hitarea").click(function() {
        $(this).parent().find("ul").remove();
        $(this).parent().find("div").removeClass("hitarea collapsable-hitarea").addClass("hitarea expandable-hitarea");
        $(this).parent().find("div").bind("click", setClickTree);
        return;
    });
    $(clicked).parent().removeClass("expandable").addClass("collapsable").append(myUL);
    $(clicked).parent().find("ul").find(".hitarea").click(setClickTree);
}

function orderChannelList(move) {
    doPostBack("Canais/" + move + "/" + $("#channelList option:selected").val(), "&pid=" + $("#channelID").val());
}

function addChannel() {
    var parent_id = $("#channelID").val();
    var channelType = $("#newType option:selected").val();
    var rss = $("#hasrss option:selected").val();
    var template = $("#template option:selected").val();
    var url = $("#url").val();

    if (checkForInvalidValue($("#newName"))) {
        doPostBack("/Canais/Add", "parent=" + parent_id + "&channel=" + channelType + "&rss=" + rss + "&template=" + template + "&name=" + $("#newName").val() + "&url=" + url + "&common=" + $("#common").val());
    }
}

function removeChannel() {
    if ($("#channelList option:selected").length > 0) {
        if (confirm(langOptions.AreYouSureDelete)) {
            doPostBack("Canais/Delete/" + $("#channelList option:selected").val(), "");
        }
    }
}

function loadChannel(id) {
    doPostBack("/Canais/Edit/" + id, null, GetChannel);
}

function GetChannel(data) {
    if (data) {
        var channel = data.channel;
        $("#name").val(channel.name);
        $("#channeltype option").each(function() {
            if ($(this).val() == channel.datatype) {
                $(this).attr('selected', 'selected');
            }
        });
        $("#channelID").val(channel.id);
        $("#channelList option").remove();

        if (channel.rss) {
            $("#uhasrss option").eq(1).attr("selected", "selected");
        } else {
            $("#uhasrss option").eq(0).attr("selected", "selected");
        }

        $("#uurl").val(channel.url);
        $("#ucommon").val(channel.common);
        
        
        $("#utemplate option").each(function() {
            if ($(this).val() == channel.template)
                $(this).attr("selected", "selected");
        });
        
        var optList = "";
        if (data.chids) {
            for (iCount = 0; iCount < data.chids.length; iCount++) {
                var ch = data.chids[iCount];
                optList += "<option value=\"" + ch.id + "\">" + ch.name + "</option>";
            }
        }
        $("#channelList").html(optList);
    }
}

function updateChannel() {
    doPostBack("/Canais/Update/" + $("#channelID").val(), "name=" + $("#name").val() + "&channel=" + $("#channeltype option:selected").val() + "&rss=" + $("#uhasrss option:selected").val() + "&template=" + $("#utemplate option:selected").val() + "&url=" + $("#uurl").val() + "&common=" + $("#ucommon").val(), updateSuccess)
}

function updateSuccess(data) {
    if (data.type == 1) {
        clearForm();
        $("#channelID").val(0);
    } else if (data.msg)
        alert(data.msg);
}

function doPostBack(url, data, func) {
    $.ajax({
        type: "POST",
        url: url,
        data: data,
        processData: false,
        dataType: "json",
        success: function(msg) {
            if (func) {
                func(msg);
            } else {
                if (msg.type == 0) {
                    if ($("#errMsg").length > 0) {
                        $("#errMsg").html(msg.msg);
                    } else {
                        alert(msg.msg);
                    }
                } else {
                    eval(msg.action);
                }
            }
        },
        error: function(req, status, err) {
            if (req.status == 500) {
                alert(req.responseText);
            } else if (req.status == 200) {
                alert("200: A sua sessão expirou\nVia ser redireccionado para a página de login")
                document.location.reload(); // = "/";
            } else if (req.status == 302) {
                alert("302: A sua sessão expirou\nVia ser redireccionado para a página de login")
                document.location.reload(); // = "/";
            }
        }
    });
}

function moveItem(from, to) {
    $("#" + from + " option:selected").appendTo($("#" + to));
}

function getOption(url, obj) {
    $(".menu_interno ul li").removeClass("active");
    $('#container').load(url);
    $(obj).parent().addClass("active");
}

function makeTable(){
	var nRows = $("#Cols").val(); 
	var nCols = $("#Rows").val();

	if(isNaN(nRows) || isNaN(nCols)){
		return;
	}
		
	var myTable = "<table border=\"1\" width=\"100%\" class=\"" + $("#cssName").val() + "\">";
	myTable +="<thead>";
	myTable +="<tr>";
	for(var mCount = 0; mCount < nCols; mCount++){
		tdClass = '';
		if(mCount == 0) tdClass = 'first';
		if(mCount == nCols - 1) tdClass = 'last';
		if(tdClass != '') tdClass = ' class="' + tdClass + '"';
		
		myTable +="<th" + tdClass + "></th>";
	}
	myTable +="<tr>";
	myTable +="</thead>";
	
	if(nRows > 1){
		myTable +="<tbody>";

		for(var iCount=1; iCount < nRows; iCount++){
			myTable +="<tr>"

			for(var mCount = 0; mCount < nCols; mCount++){
				tdClass = '';
				if(mCount == 0) tdClass = 'first';
				if(mCount == nCols - 1) tdClass = 'last';
				if(tdClass != '') tdClass = ' class="' + tdClass + '"';

				myTable +="<td" + tdClass + "></td>";
			}

			myTable +="</tr>";
		}
		
		myTable +="</tbody>";
	}
	myTable +="</table>";
   
    CKEDITOR.instances.html.setData(CKEDITOR.instances.html.getData() + myTable);
}

function saveMap(){
    if($("#map_type").val()==""){
        alert("Please choose a map type!");
        return ;
    }
    
    var isOk2Go = true;
    
    if (!checkForInvalidValue($("#name"))) isOk2Go = false;
    if (!checkForInvalidValue($("#Country"))) isOk2Go = false;
    //if (!checkForInvalidValue($("#region"))) isOk2Go = false;
    if (!checkForInvalidValue($("#latitude"))) isOk2Go = false;
    if (!checkForInvalidValue($("#longitude"))) isOk2Go = false;

    if(isNaN($("#latitude").val())){
        $("#latitude").animate({ backgroundColor: "#D0AFAE" });
        isOk2Go = false;
    }else{
        if(parseFloat($("#latitude").val()) < -90 || parseFloat($("#latitude").val()) > 90){
            $("#latitude").animate({ backgroundColor: "#D0AFAE" });
            isOk2Go = false;    
        }
    }
    
    if(isNaN($("#longitude").val())){
        $("#longitude").animate({ backgroundColor: "#D0AFAE" });
        isOk2Go = false;
    }else {
        if(parseFloat($("#longitude").val()) < -180 || parseFloat($("#longitude").val()) > 180){
            $("#longitude").animate({ backgroundColor: "#D0AFAE" });
            isOk2Go = false;    
        }
    }
    
    if($("#map_type").val()!="where_are_we"){
        var rules = /^([0-9]{2}\.[0-9]{2}\.[0-9]{4})$/i;
        if(!rules.test($("#started").val())){
            $("#started").animate({ backgroundColor: "#D0AFAE" });
            isOk2Go = false;        
        }
        if(isNaN($("#capacity").val())){
            $("#capacity").animate({ backgroundColor: "#D0AFAE" });
            isOk2Go = false;
        }
        if(isNaN($("#generator").val())){
            $("#generator").animate({ backgroundColor: "#D0AFAE" });
            isOk2Go = false;
        }
    }
    
    if (isOk2Go){
        if($("#id").length>0)
            doPostBack("/Map/Edit/", $("#itemForm").serialize())    
        else
            doPostBack("/Map/Add/", $("#itemForm").serialize())    
    }
}
