/* Minification failed. Returning unminified contents.
(869,4041-4048): run-time warning JS1028: Expected identifier or string: default
(869,5824-5831): run-time warning JS1010: Expected identifier: default
(869,6186-6193): run-time warning JS1010: Expected identifier: default
(869,8000-8007): run-time warning JS1028: Expected identifier or string: default
(869,9754-9761): run-time warning JS1010: Expected identifier: default
(869,9961-9968): run-time warning JS1010: Expected identifier: default
(869,10711-10718): run-time warning JS1010: Expected identifier: default
(869,5824-5831): run-time error JS1137: 'default' is a new reserved word and should not be used as an identifier: default
(869,6186-6193): run-time error JS1137: 'default' is a new reserved word and should not be used as an identifier: default
(869,9754-9761): run-time error JS1137: 'default' is a new reserved word and should not be used as an identifier: default
(869,9961-9968): run-time error JS1137: 'default' is a new reserved word and should not be used as an identifier: default
(869,10711-10718): run-time error JS1137: 'default' is a new reserved word and should not be used as an identifier: default
 */
var Util = {};

Util.get = function (key) {
    return $(key).val();
};

Util.set = function (key, value) {
    $(key).val(value);
};

Util.setEditor = function (e, value) {
    e.setValue(value);
};


//http://stackoverflow.com/questions/21647928/javascript-unicode-string-to-hex
//unicode
String.prototype.hexEncode = function () {
    var hex, i;

    var result = "";
    for (i = 0; i < this.length; i++) {
        hex = this.charCodeAt(i).toString(16);
        result += ("000" + hex).slice(-4);
    }

    return result
}

String.prototype.hexDecode = function () {
    var j;
    var hexes = this.match(/.{1,4}/g) || [];
    var back = "";
    for (j = 0; j < hexes.length; j++) {
        back += String.fromCharCode(parseInt(hexes[j], 16));
    }

    return back;
}

//or
function d2h(d) {
    return d.toString(16);
}
function h2d(h) {
    return parseInt(h, 16);
}
function string2Hex(tmp) {
    var str = '',
            i = 0,
            tmp_len = tmp.length,
            c;

    for (; i < tmp_len; i += 1) {
        c = tmp.charCodeAt(i);
        str += d2h(c) + ' ';
    }
    return str;
}
function hex2String(tmp) {
    var arr = tmp.split(' '),
            str = '',
            i = 0,
            arr_len = arr.length,
            c;

    for (; i < arr_len; i += 1) {
        c = String.fromCharCode(h2d(arr[i]));
        str += c;
    }

    return str;
}
//or

function stringToHex(tmp) {
    var str = '';
    for (var i = 0; i < tmp.length; i++) {
        c = tmp.charCodeAt(i);
        //str += d2h(c) + ' '; // Add Hex Space
        str += d2h(c);
    }
    return str;
}
function hexToString(tmp) {
    //var arr = tmp.split(' ');
    var str = '';
    // Hex Containing Spaces
    //        for (var i = 0; i < arr.length; i++) {
    //            c = String.fromCharCode(h2d(arr[i]));
    //            str += c;
    //        }
    for (var i = 0; i < tmp.length; i += 2) {
        str += String.fromCharCode(parseInt(tmp.substr(i, 2), 16));
    }
    return str;
}
function baseToBaseConversion(str, fromBase, toBase) {

    var num = parseInt(str, fromBase);
    if (str.trim() != "") {
        var result = num.toString(toBase);

        if (result.toString() == "NaN") {
            result = "Invalid Input";
        }
        return result;
    }
    else {
        return;
    }
}

//function stringToBinary(str) {
//    var st, i, j, d;
//    var arr = [];
//    var len = str.length;
//    for (i = 1; i <= len; i++) {
//        //reverse so its like a stack
//        d = str.charCodeAt(len - i);
//        for (j = 0; j < 8; j++) {
//            arr.push(d % 2);
//            d = Math.floor(d / 2);
//        }
//    }
//    //reverse all bits again.
//    return arr.reverse().join("");
//}

//function binaryToString(binary) {
//    var output ="";
//    var input = binary;
//    for (i = 0; i < input.length; i++) {
//        output += input[i].charCodeAt(0).toString(2) + " ";
//    }
//    return output;
//}

//[or]

// ABC - a generic, native JS (A)scii(B)inary(C)onverter.
// (c) 2013 Stephan Schmitz <eyecatchup@gmail.com>
// License: MIT, http://eyecatchup.mit-license.org
// URL: https://gist.github.com/eyecatchup/6742657
var ABC = {
    toAscii: function (bin) {
        return bin.replace(/\s*[01]{8}\s*/g, function (bin) {
            return String.fromCharCode(parseInt(bin, 2))
        })
    },
    toBinary: function (str, spaceSeparatedOctets) {
        return str.replace(/[\s\S]/g, function (str) {
            str = ABC.zeroPad(str.charCodeAt().toString(2));
            return !1 == spaceSeparatedOctets ? str : str + " "
        })
    },
    zeroPad: function (num) {
        return "00000000".slice(String(num).length) + num
    }
};


// Convert numbers to words
// copyright 25th July 2006, by Stephen Chapman http://javascript.about.com
// permission to use this Javascript on your web page is granted
// provided that all of the code (including this copyright notice) is
// used exactly as shown (you can change the numbering system if you wish)
// American Numbering System
var th = ['', 'thousand', 'million', 'billion', 'trillion'];
// uncomment this line for English Number System
// var th = ['','thousand','million', 'milliard','billion'];

var dg = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
var tn = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
var tw = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];

function ToWords(s) {
    s = s.toString();
    s = s.replace(/[\, ]/g, '');
    if (s != parseFloat(s)) return 'not a number';
    var x = s.indexOf('.');
    if (x == -1) x = s.length;
    if (x > 15) return 'too big';
    var n = s.split('');
    var str = '';
    var sk = 0;
    for (var i = 0; i < x; i++) {
        if ((x - i) % 3 == 2) {
            if (n[i] == '1') {
                str += tn[Number(n[i + 1])] + ' ';
                i++;
                sk = 1;
            } else if (n[i] != 0) {
                str += tw[n[i] - 2] + ' ';
                sk = 1;
            }
        } else if (n[i] != 0) {
            str += dg[n[i]] + ' ';
            if ((x - i) % 3 == 0) str += 'hundred ';
            sk = 1;
        }
        if ((x - i) % 3 == 1) {
            if (sk) str += th[(x - i - 1) / 3] + ' ';
            sk = 0;
        }
    }
    if (x != s.length) {
        var y = s.length;
        str += 'point ';
        for (var i = x + 1; i < y; i++) str += dg[n[i]] + ' ';
    }
    return str.replace(/\s+/g, ' ');
}


var a = ['', 'one ', 'two ', 'three ', 'four ', 'five ', 'six ', 'seven ', 'eight ', 'nine ', 'ten ', 'eleven ', 'twelve ', 'thirteen ', 'fourteen ', 'fifteen ', 'sixteen ', 'seventeen ', 'eighteen ', 'nineteen '];
var b = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];

function InWords(num) {
    if ((num = num.toString()).length > 9) return 'overflow';
    n = ('000000000' + num).substr(-9).match(/^(\d{2})(\d{2})(\d{2})(\d{1})(\d{2})$/);
    if (!n) return; var str = '';
    str += (n[1] != 0) ? (a[Number(n[1])] || b[n[1][0]] + ' ' + a[n[1][1]]) + 'crore ' : '';
    str += (n[2] != 0) ? (a[Number(n[2])] || b[n[2][0]] + ' ' + a[n[2][1]]) + 'lakh ' : '';
    str += (n[3] != 0) ? (a[Number(n[3])] || b[n[3][0]] + ' ' + a[n[3][1]]) + 'thousand ' : '';
    str += (n[4] != 0) ? (a[Number(n[4])] || b[n[4][0]] + ' ' + a[n[4][1]]) + 'hundred ' : '';
    str += (n[5] != 0) ? ((str != '') ? 'and ' : '') + (a[Number(n[5])] || b[n[5][0]] + ' ' + a[n[5][1]]) + 'only ' : '';
    return str;
    //}
}

// encode(decode) html text into html entity
var decodeHtmlEntity = function (str) {
    return str.replace(/&#(\d+);/g, function (match, dec) {
        return String.fromCharCode(dec);
    });
};

var encodeHtmlEntity = function (str) {
    var buf = [];
    for (var i = str.length - 1; i >= 0; i--) {
        buf.unshift(['&#', str[i].charCodeAt(), ';'].join(''));
    }
    return buf.join('');
};

//Encode URL String
function EncodeUrl(url) {
    return encodeURIComponent(url);
}

//Decode URL String
function DecodeUrl(url) {
    return decodeURIComponent(url);
}

//what is _ % of _
function perc1(a, b) {
    return a / 100 * b;;
}
//_ is what % of _
function perc2(a, b) {
    return a / b * 100; ;
}
//what is _ % increase/ decrease
function perc3(a, b) {
    return (b - a) / a * 100;
}

function is_valid_email($email) {
    if (preg_match("/[a-zA-Z0-9_-.+]+@[a-zA-Z0-9-]+.[a-zA-Z]+/", $email) > 0)
        return true;
    else
        return false;
}

function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

// Hash any string into an integer value
// Then we'll use the int and convert to hex.
function hashCode(str) {
    var hash = 0;
    for (var i = 0; i < str.length; i++) {
        hash = str.charCodeAt(i) + ((hash << 5) - hash);
    }
    return hash;
}

// https: //www.designedbyaturtle.co.uk/2014/convert-string-to-hexidecimal-colour-with-javascript-vanilla/
// Convert an int to hexadecimal with a max length
// of six characters.
function intToARGB(i) {
    var hex = ((i >> 24) & 0xFF).toString(16) +
            ((i >> 16) & 0xFF).toString(16) +
            ((i >> 8) & 0xFF).toString(16) +
            (i & 0xFF).toString(16);
    // Sometimes the string returned will be too short so we 
    // add zeros to pad it out, which later get removed if
    // the length is greater than six.
    hex += '000000';
    return hex.substring(0, 6);
}

// Extend the string type to allow converting to hex for quick access.
String.prototype.toHexColour = function () {
    return intToARGB(hashCode(this));
}

//modify - CB
function decodeSpecialCharacter(str) {
    return str.replace(/\&amp;/g, '&').replace(/\&gt;/g, '>').replace(/\&lt;/g,
			'<').replace(/\&quot;/g, '"');
}

function looks_like_html(source) {
    // <foo> - looks like html
    // <!--\nalert('foo!');\n--> - doesn't look like html

    var trimmed = source.replace(/^[ \t\n\r]+/, '');
    var comment_mark = '<' + '!-' + '-';
    return (trimmed && (trimmed.substring(0, 1) === '<' && trimmed.substring(0, 4) !== comment_mark));
};var Settings = {
    HttpsEnabled: true,
    SaveAnalytics: false
};;/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
var saveAs=saveAs||function(e){"use strict";if("undefined"==typeof navigator||!/MSIE [1-9]\./.test(navigator.userAgent)){var t=e.document,n=function(){return e.URL||e.webkitURL||e},o=t.createElementNS("http://www.w3.org/1999/xhtml","a"),r="download"in o,i=function(n){var o=t.createEvent("MouseEvents");o.initMouseEvent("click",!0,!1,e,0,0,0,0,0,!1,!1,!1,!1,0,null),n.dispatchEvent(o)},a=e.webkitRequestFileSystem,c=e.requestFileSystem||a||e.mozRequestFileSystem,u=function(t){(e.setImmediate||e.setTimeout)(function(){throw t},0)},f="application/octet-stream",s=0,d=500,l=function(t){var o=function(){"string"==typeof t?n().revokeObjectURL(t):t.remove()};e.chrome?o():setTimeout(o,d)},v=function(e,t,n){t=[].concat(t);for(var o=t.length;o--;){var r=e["on"+t[o]];if("function"==typeof r)try{r.call(e,n||e)}catch(i){u(i)}}},p=function(e){return/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(e.type)?new Blob(["\ufeff",e],{type:e.type}):e},w=function(t,u){t=p(t);var d,w,y,m=this,S=t.type,h=!1,O=function(){v(m,"writestart progress write writeend".split(" "))},E=function(){if((h||!d)&&(d=n().createObjectURL(t)),w)w.location.href=d;else{var o=e.open(d,"_blank");void 0==o&&"undefined"!=typeof safari&&(e.location.href=d)}m.readyState=m.DONE,O(),l(d)},R=function(e){return function(){return m.readyState!==m.DONE?e.apply(this,arguments):void 0}},b={create:!0,exclusive:!1};return m.readyState=m.INIT,u||(u="download"),r?(d=n().createObjectURL(t),o.href=d,o.download=u,i(o),m.readyState=m.DONE,O(),void l(d)):(e.chrome&&S&&S!==f&&(y=t.slice||t.webkitSlice,t=y.call(t,0,t.size,f),h=!0),a&&"download"!==u&&(u+=".download"),(S===f||a)&&(w=e),c?(s+=t.size,void c(e.TEMPORARY,s,R(function(e){e.root.getDirectory("saved",b,R(function(e){var n=function(){e.getFile(u,b,R(function(e){e.createWriter(R(function(n){n.onwriteend=function(t){w.location.href=e.toURL(),m.readyState=m.DONE,v(m,"writeend",t),l(e)},n.onerror=function(){var e=n.error;e.code!==e.ABORT_ERR&&E()},"writestart progress write abort".split(" ").forEach(function(e){n["on"+e]=m["on"+e]}),n.write(t),m.abort=function(){n.abort(),m.readyState=m.DONE},m.readyState=m.WRITING}),E)}),E)};e.getFile(u,{create:!1},R(function(e){e.remove(),n()}),R(function(e){e.code===e.NOT_FOUND_ERR?n():E()}))}),E)}),E)):void E())},y=w.prototype,m=function(e,t){return new w(e,t)};return"undefined"!=typeof navigator&&navigator.msSaveOrOpenBlob?function(e,t){return navigator.msSaveOrOpenBlob(p(e),t)}:(y.abort=function(){var e=this;e.readyState=e.DONE,v(e,"abort")},y.readyState=y.INIT=0,y.WRITING=1,y.DONE=2,y.error=y.onwritestart=y.onprogress=y.onwrite=y.onabort=y.onerror=y.onwriteend=null,m)}}("undefined"!=typeof self&&self||"undefined"!=typeof window&&window||this.content);"undefined"!=typeof module&&module.exports?module.exports.saveAs=saveAs:"undefined"!=typeof define&&null!==define&&null!=define.amd&&define([],function(){return saveAs});;var editorType;


//to fix button group tooltip hover issue
//$(document).ready(function () {
//    $('.btn-group [title]').tooltip({
//        container: 'body'
//    });
//})


var isSave =false, isFork = false, isShare = false;

//initialize tootip
$(function () {
    $('[data-toggle="tooltip"]').tooltip({
        trigger: "hover",
        container: 'body' //to fix button group tooltip hover issue
    });

    $('[data-toggle="popover"]').popover();
});


//$("#btn_fork").css("display", "none");
//$("#btn_share").css("display", "none");
$(document).ready(function () {
    var ucid = $("#ucid").val();
    if (ucid != null && $.trim(ucid).length > 0) {
        $("#btn_share").hide();
        $("#btn_fork").show();
    }
    else {
        $("#btn_fork").hide();
        $("#btn_share").show();
    }
    $("#ucPublic").attr('checked', true);
});

//$('#copy_editor').tooltip({
//    trigger: "manual"
//})

//$('#copy_editor').on('mouseenter', function () {
//    var tt = $(this);
//    if (tt.attr('data-original-title') != 'copied!')
//        tt.tooltip("show");
//});

//$('#copy_editor').on('mouseleave', function () {
//    var tt = $(this);


//    if (tt.attr('data-original-title') != 'copied!')
//        tt.tooltip("hide");
//});

function SaveFile(data, fileName) {
    var blob = new Blob([data],
    { type: "text/plain;charset=utf-8" });
    saveAs(blob, fileName + "." + ext);
}
//function Clear(id) {
//    $(id).val('');
//}
//function ClearEditor() {
//    editor.setValue('');
//}

function Clear(type, id) {
    if (type == 'E')//Ace Editor
        id.setValue('');
    else if (type == 'T')//Text Editor
        $(id).val('');
}
//function ClearEditor() {
//    editor.setValue('');
//}

function Copy(type, id) {
    if (type == 'E')//Ace Editor
        clip.setData(id.getValue());
    else if (type == 'T')//Text Editor
        clip.setData($(id).val());
}

function sample(sdata, editorType, id) {
    $.ajax({
        type: "GET",
        url: rootUrl + "CodeSamples/Sample",
        //contentType: "application/json",
        data: { uid: sdata },
        success: function (resp) {
            if (editorType == 'editor')
                fillEditor(iEditor, resp); // editor.setValue(resp);
            else if (editorType == 'tarea')
                $(id).val(resp);
            else if (editorType == 'ioeditor') {
                if (sdata.indexOf('_xml') > 0) {
                    fillEditor(iEditor, resp);
                    sample(sdata.replace('_xml', '_xsl'), 'ioeditor');
                }
                else if (sdata.indexOf('_ijson') > 0) {
                    fillEditor(iEditor, resp);
                    sample(sdata.replace('_ijson', '_ojson'), 'ioeditor');
                }
                else
                    fillEditor(oEditor, resp); //editorsec.setValue(resp);
            }
        }
    });
}

function loadFromUrl(udata, eType, id) {
    editorType = eType;
    $.ajax({
        type: "GET",
        url: rootUrl + "Common/LoadFromUrl",
        data: { url: udata },
        success: function (resp) {
            if (editorType == 'editor')
                iEditor.setValue(resp);
            else if (editorType == 'tarea')
                $(id).val(resp);
        }
    });
}

//function dataFromUrl(udata) {
//    $.ajax({
//        type: "GET",
//        url: rootUrl + "Common/LoadFromUrl",
//        data: { url: udata },
//        success: function (resp) {
//            editor.setValue(resp);
//        }
//    });
//}

$('.file-upload').click(function () {
    editorType = 'editor'
    $('input[type=file]').trigger('click');
});

$('#fileuploadTE').click(function () {
    editorType = 'tarea'
    $('input[type=file]').trigger('click');
});

//$('input[type=file]').change(function () {
//    //    var vals = $(this).val(),
//    //        val = vals.length ? vals.split('\\').pop() : '';

//    //    $('input[type=text]').val(val);

//    //http: //www.w3schools.com/jsref/prop_fileupload_files.asp
//    //    var x = document.getElementById("myFile");
//    //    var txt = "";
//    //    if ('files' in x) {
//    //        if (x.files.length == 0) {
//    //            txt = "Select one or more files.";
//    //        } else {
//    //            for (var i = 0; i < x.files.length; i++) {
//    //                txt += "<br><strong>" + (i + 1) + ". file</strong><br>";
//    //                var file = x.files[i];
//    //                if ('name' in file) {
//    //                    txt += "name: " + file.name + "<br>";
//    //                }
//    //                if ('size' in file) {
//    //                    txt += "size: " + file.size + " bytes <br>";
//    //                }
//    //            }
//    //        }
//    //    }
//    //    document.getElementById("demo").innerHTML = txt;
//    //http://blog.teamtreehouse.com/reading-files-using-the-html5-filereader-api
////    var reader = new FileReader();

////    reader.onload = function (e) {
////        var text = reader.result;
////        editor.setValue(text);
////    }

//    
//    alert('file');
//});

//Handles multiple file upload. modify it
$('input[type=file]').on('change', function (e) {
    var files = e.target.files;
    //var myID = 3; //uncomment this to make sure the ajax URL works
    if (files.length > 0) {
        if (window.FormData !== undefined) {
            var data = new FormData();
            for (var x = 0; x < files.length; x++) {
                data.append("file" + x, files[x]);
            }
            var id = $('#load-url').data('id');
            $.ajax({
                type: "POST",
                url: rootUrl + 'Common/LoadFromFile', //?id=' + myID,
                contentType: false,
                processData: false,
                data: data,
                success: function (result) {
                    if (editorType == 'editor')
                        iEditor.setValue(result);
                    else (editorType == 'tarea')
                    $(id).val(result);
                },
                error: function (xhr, status, p3, p4) {
                    var err = "Error " + " " + status + " " + p3 + " " + p4;
                    if (xhr.responseText && xhr.responseText[0] == "{")
                        err = JSON.parse(xhr.responseText).Message;
                    console.log(err);
                }
            });
        } else {
            alert("This browser doesn't support HTML5 file uploads!");
        }
    }
});

//function getSample() {
//    $.ajax({
//        type: "GET",
//        url: rootUrl + "CodeSamples/Sample",
//        //contentType: "application/json",
//        data: { uid: sdata },
//        success: function (resp) {
//            editor.setValue(resp);
//        }
//    });
//}

function Analytics() {

    if (Settings.SaveAnalytics) {
        var hurl = $("#hurl").val();

        var ucid = $("#ucid").val();
        if (ucid !== null && $.trim(ucid).length > 0) {
            var url = hurl.split('/');
            url.splice(-1, 1);
            hurl = (url.join('/')) + '-U';
        }
        //alert(hurl);
        var analytics = {
            Url: hurl,
            Content: null
        };
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: rootUrl + 'Common/Analytics',
            data: JSON.stringify(analytics),
            success: function (result) {

            },
            error: function (e) {

            }
        });
    }
}


var statusDisp = { success: { type: "success", icon: "ok" },
    failure: { type: "danger", icon: "remove" },
    warning: { type: "warning", icon: "exclamation-sign" }
};

if ($('#ucTitle').length > 0 && $('#ucTitle').val().length < 3) {
    $('#modalsubmit').prop('disabled', true);
}

$("#ucTitle").on('keyup', function () {
    $('#modalsubmit').prop('disabled', ($(this).val().length < 3));
});



function Share() {
    StatusClear();
    isShare = true;
    SaveModal();

}

function Fork() {
    StatusClear();
    isFork = true;
    var hurl = $("#hurl").val();
    hurl = hurl.replace("/" + $("#ucid").val(), "");
    $("#hurl").val(hurl);
    $("#ucid").val("");
    SaveModal();

}

function Save() {
    StatusClear();
    isSave = true;
    SaveModal();
}

function SaveModal() {
    var ucid = $("#ucid").val();
    if (iEditor)
        data = iEditor.getValue();
    else if ($('#baseText').length > 0)
        data = $('#baseText').val();

    isSave ? $("#ucPublicPnl").show() : $("#ucPublicPnl").hide();

    if (data && (data.length > 0)) {
        if (ucid == null || $.trim(ucid).length == 0)
            $("#myModal").modal();
        else {
            SaveRepo(ucid);
        }
    }
    else {
        StatusGenerate("Please enter your content", statusDisp.failure, true);
    }
}

function SaveRepo(id) {
    //alert($("#hurl").val());
    var ucid = $("#ucid").val();

    var data;
    if (iEditor)
        data = iEditor.getValue();
    else if ($('#baseText').length > 0)
        data = $('#baseText').val();

    if (!data && !(data.length > 0))
        return;
    

    var userConverter = {
        UserConverterEId: ucid,
        ConverterId: id,
        ConverterKey: $("#hurl").val(),
        Title: $("#ucTitle").val(),
        Description: $("#ucDescription").val(),
        IsPrivate: (isShare || isFork) ? true : $("#ucPublic").is(":checked"),
        input: data
    };

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: rootUrl + 'Common/Save',
        data: JSON.stringify(userConverter),
        success: function (result) {
            if (isFork) {
                window.location = $("#hurl").val() + "/" + result;
            }
            else {
                //alert(result);
                StatusGenerate("Saved successfully!", statusDisp.success, true);
                $("#ucid").val(result);
                ModalClear();
                $("#myModal").modal('hide');

                //console.log($("#hurl").val() + "/" + result);
                if (!ucid) {
                    var shareUrl = $("#hurl").val() + "/" + result;
                    var shareAnchor = $('<a href="' + shareUrl + '"><i class="fa fa-share-alt"></i>' + shareUrl + '</a>')
                    $("#sharelink").html(shareAnchor);
                }
            }
        },
        error: function (e) {

        }
    });
}

$(".btn-edit-repo").click(function () {
    var con = $(this);
    $("#ucid").val(con.data('ucid'));
    $("#ucTitle").val(con.data('title'));
    $("#ucDescription").val(con.data('description'));
    $("#ucPublic").prop('checked', con.data('isprivate') === "True");

    $('#modalsubmit').prop('disabled', con.data('title').length < 3);

    $("#editModal").modal();
});

function EditRepo() {
    var userConverter = {
        UserConverterEId: $("#ucid").val(),
        Title: $("#ucTitle").val(),
        Description: $("#ucDescription").val(),
        IsPrivate: $("#ucPublic").is(":checked")
    };

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: rootUrl + 'Common/Update',
        data: JSON.stringify(userConverter),
        success: function (result) {
            StatusGenerate("Saved successfully!", statusDisp.success, true);
            $("#ucid").val(result);
            ModalClear();
            $("#myModal").modal('hide');
        },
        error: function (e) {

        }
    });
}

$(document).ready(function () {
    if (!($("#ucid").length > 0))
        return;

    var ucid = $("#ucid").val();

    if (!ucid && !(ucid.length > 0))
        return;

    var param = {
        id: ucid
    };

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: rootUrl + 'UserConverter/Repository',
        data: JSON.stringify(param),
        success: function (result) {
            if (iEditor)
                fillEditor(iEditor, result)
            else if ($('#baseText').length > 0)
                $('#baseText').val(result);
        },
        error: function (e) {

        }
    });

});

function ModalClear() {
    $("#ucTitle").empty();
    $("#ucDescription").empty();
    $("#ucPublic").attr('checked', true);
}

function StatusGenerate(msg, sType, hideStatus) {
    var statusContent =
    '<div id="status" class="alert alert-' + sType.type + '" role="alert">  ' +
 '   <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>  ' +
 '     <span class="glyphicon glyphicon-' + sType.icon + '" aria-hidden="true"></span>  ' +
 '     <span class="sr-only">Error:</span>  ' +
 '     ' + msg + '  ' +
 '  </div>  ';

    $("#status").empty().append(statusContent);

    if (hideStatus) {
        scrollTop("#status");
        setTimeout(function () {
            $("#status").fadeOut(1000, function () {
                $("#status").empty();
                $("#status").show();
            });

        }, 10000);
    }
}

function StatusClear() {
    $("#status").empty();

    isFork = false, isSave = false, isShare = false;
}
function OutputClear() {
    $("#output").empty();
}

//To scroll to top of page call w/o id parameter. 
function scrollTop(id) {
    $('html, body').animate({ scrollTop: (id ? $(id).position().top : 0)}, 'slow');
}

$(".e-resize").click(function () {
    var panel = $(this).data('resize');

    var editorL = $('#editor').parent();
    var editorR = $('#oeditor, #oviewer').parent();
    var isExpanded = $(editorL).hasClass('col-md-12');
    
    $(editorL).removeClass('col-md-' + (isExpanded ? '12':'6')).addClass('col-md-' + (isExpanded ? '6':'12'));
    $(editorR).removeClass('col-md-' + (isExpanded ? '12' : '6')).addClass('col-md-' + (isExpanded ? '6' : '12'));

    $('.e-resize').children('span').removeClass(isExpanded ? 'glyphicon-resize-small' : 'glyphicon-resize-full').addClass(isExpanded ? 'glyphicon-resize-full' : 'glyphicon-resize-small');
    $('.e-resize').attr('data-original-title', (isExpanded ? 'expand' : 'collapse')).tooltip('hide');

    var scrollLocation = panel === 'out' ? (isExpanded ? null : '#e-out') : '.article';
    scrollTop(scrollLocation);

    //$('html, body').animate({ scrollTop: (panel === 'out' ? 0 : $('.article').position().top)  }, 'slow');
    

    //if ($(this).hasClass('fa-arrows-alt')) {
    //    $(this).removeClass('fa-arrows-alt').addClass('fa-expand');
    //    panels.forEach(function (val) {
    //        $('#pnl-' + val).attr('class', "col-md-4");
    //        var icons = '#pnl-' + val + ' .fa-cog, ' + '#pnl-' + val + ' .fa-align-left, ' + '#pnl-' + val + ' span.fa';
    //        $(icons).show();
    //    });
    //}
    //else {
    //    panels.forEach(function (val) {
    //        var icons = '#pnl-' + val + ' .fa-cog, ' + '#pnl-' + val + ' .fa-align-left, ' + '#pnl-' + val + ' span.fa';
    //        if (panel === val) {
    //            $('#pnl-' + val).attr('class', "col-md-10");
    //            $(icons).show();
    //            $('#pnl-' + val + ' i.resize').addClass('fa-arrows-alt').removeClass('fa-expand');
    //        }
    //        else {
    //            $('#pnl-' + val).attr('class', "col-md-1");
    //            $(icons).hide();
    //            $('#pnl-' + val + ' i.resize').removeClass('fa-arrows-alt').addClass('fa-expand');
    //        }
    //    });
    //}

});;/*!
 * clipboard.js v1.7.1
 * https://zenorocha.github.io/clipboard.js
 *
 * Licensed MIT © Zeno Rocha
 */
!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.Clipboard=t()}}(function(){var t,e,n;return function t(e,n,o){function i(a,c){if(!n[a]){if(!e[a]){var l="function"==typeof require&&require;if(!c&&l)return l(a,!0);if(r)return r(a,!0);var s=new Error("Cannot find module '"+a+"'");throw s.code="MODULE_NOT_FOUND",s}var u=n[a]={exports:{}};e[a][0].call(u.exports,function(t){var n=e[a][1][t];return i(n||t)},u,u.exports,t,e,n,o)}return n[a].exports}for(var r="function"==typeof require&&require,a=0;a<o.length;a++)i(o[a]);return i}({1:[function(t,e,n){function o(t,e){for(;t&&t.nodeType!==i;){if("function"==typeof t.matches&&t.matches(e))return t;t=t.parentNode}}var i=9;if("undefined"!=typeof Element&&!Element.prototype.matches){var r=Element.prototype;r.matches=r.matchesSelector||r.mozMatchesSelector||r.msMatchesSelector||r.oMatchesSelector||r.webkitMatchesSelector}e.exports=o},{}],2:[function(t,e,n){function o(t,e,n,o,r){var a=i.apply(this,arguments);return t.addEventListener(n,a,r),{destroy:function(){t.removeEventListener(n,a,r)}}}function i(t,e,n,o){return function(n){n.delegateTarget=r(n.target,e),n.delegateTarget&&o.call(t,n)}}var r=t("./closest");e.exports=o},{"./closest":1}],3:[function(t,e,n){n.node=function(t){return void 0!==t&&t instanceof HTMLElement&&1===t.nodeType},n.nodeList=function(t){var e=Object.prototype.toString.call(t);return void 0!==t&&("[object NodeList]"===e||"[object HTMLCollection]"===e)&&"length"in t&&(0===t.length||n.node(t[0]))},n.string=function(t){return"string"==typeof t||t instanceof String},n.fn=function(t){return"[object Function]"===Object.prototype.toString.call(t)}},{}],4:[function(t,e,n){function o(t,e,n){if(!t&&!e&&!n)throw new Error("Missing required arguments");if(!c.string(e))throw new TypeError("Second argument must be a String");if(!c.fn(n))throw new TypeError("Third argument must be a Function");if(c.node(t))return i(t,e,n);if(c.nodeList(t))return r(t,e,n);if(c.string(t))return a(t,e,n);throw new TypeError("First argument must be a String, HTMLElement, HTMLCollection, or NodeList")}function i(t,e,n){return t.addEventListener(e,n),{destroy:function(){t.removeEventListener(e,n)}}}function r(t,e,n){return Array.prototype.forEach.call(t,function(t){t.addEventListener(e,n)}),{destroy:function(){Array.prototype.forEach.call(t,function(t){t.removeEventListener(e,n)})}}}function a(t,e,n){return l(document.body,t,e,n)}var c=t("./is"),l=t("delegate");e.exports=o},{"./is":3,delegate:2}],5:[function(t,e,n){function o(t){var e;if("SELECT"===t.nodeName)t.focus(),e=t.value;else if("INPUT"===t.nodeName||"TEXTAREA"===t.nodeName){var n=t.hasAttribute("readonly");n||t.setAttribute("readonly",""),t.select(),t.setSelectionRange(0,t.value.length),n||t.removeAttribute("readonly"),e=t.value}else{t.hasAttribute("contenteditable")&&t.focus();var o=window.getSelection(),i=document.createRange();i.selectNodeContents(t),o.removeAllRanges(),o.addRange(i),e=o.toString()}return e}e.exports=o},{}],6:[function(t,e,n){function o(){}o.prototype={on:function(t,e,n){var o=this.e||(this.e={});return(o[t]||(o[t]=[])).push({fn:e,ctx:n}),this},once:function(t,e,n){function o(){i.off(t,o),e.apply(n,arguments)}var i=this;return o._=e,this.on(t,o,n)},emit:function(t){var e=[].slice.call(arguments,1),n=((this.e||(this.e={}))[t]||[]).slice(),o=0,i=n.length;for(o;o<i;o++)n[o].fn.apply(n[o].ctx,e);return this},off:function(t,e){var n=this.e||(this.e={}),o=n[t],i=[];if(o&&e)for(var r=0,a=o.length;r<a;r++)o[r].fn!==e&&o[r].fn._!==e&&i.push(o[r]);return i.length?n[t]=i:delete n[t],this}},e.exports=o},{}],7:[function(e,n,o){!function(i,r){if("function"==typeof t&&t.amd)t(["module","select"],r);else if(void 0!==o)r(n,e("select"));else{var a={exports:{}};r(a,i.select),i.clipboardAction=a.exports}}(this,function(t,e){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var i=n(e),r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},a=function(){function t(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}return function(e,n,o){return n&&t(e.prototype,n),o&&t(e,o),e}}(),c=function(){function t(e){o(this,t),this.resolveOptions(e),this.initSelection()}return a(t,[{key:"resolveOptions",value:function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.action=e.action,this.container=e.container,this.emitter=e.emitter,this.target=e.target,this.text=e.text,this.trigger=e.trigger,this.selectedText=""}},{key:"initSelection",value:function t(){this.text?this.selectFake():this.target&&this.selectTarget()}},{key:"selectFake",value:function t(){var e=this,n="rtl"==document.documentElement.getAttribute("dir");this.removeFake(),this.fakeHandlerCallback=function(){return e.removeFake()},this.fakeHandler=this.container.addEventListener("click",this.fakeHandlerCallback)||!0,this.fakeElem=document.createElement("textarea"),this.fakeElem.style.fontSize="12pt",this.fakeElem.style.border="0",this.fakeElem.style.padding="0",this.fakeElem.style.margin="0",this.fakeElem.style.position="absolute",this.fakeElem.style[n?"right":"left"]="-9999px";var o=window.pageYOffset||document.documentElement.scrollTop;this.fakeElem.style.top=o+"px",this.fakeElem.setAttribute("readonly",""),this.fakeElem.value=this.text,this.container.appendChild(this.fakeElem),this.selectedText=(0,i.default)(this.fakeElem),this.copyText()}},{key:"removeFake",value:function t(){this.fakeHandler&&(this.container.removeEventListener("click",this.fakeHandlerCallback),this.fakeHandler=null,this.fakeHandlerCallback=null),this.fakeElem&&(this.container.removeChild(this.fakeElem),this.fakeElem=null)}},{key:"selectTarget",value:function t(){this.selectedText=(0,i.default)(this.target),this.copyText()}},{key:"copyText",value:function t(){var e=void 0;try{e=document.execCommand(this.action)}catch(t){e=!1}this.handleResult(e)}},{key:"handleResult",value:function t(e){this.emitter.emit(e?"success":"error",{action:this.action,text:this.selectedText,trigger:this.trigger,clearSelection:this.clearSelection.bind(this)})}},{key:"clearSelection",value:function t(){this.trigger&&this.trigger.focus(),window.getSelection().removeAllRanges()}},{key:"destroy",value:function t(){this.removeFake()}},{key:"action",set:function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"copy";if(this._action=e,"copy"!==this._action&&"cut"!==this._action)throw new Error('Invalid "action" value, use either "copy" or "cut"')},get:function t(){return this._action}},{key:"target",set:function t(e){if(void 0!==e){if(!e||"object"!==(void 0===e?"undefined":r(e))||1!==e.nodeType)throw new Error('Invalid "target" value, use a valid Element');if("copy"===this.action&&e.hasAttribute("disabled"))throw new Error('Invalid "target" attribute. Please use "readonly" instead of "disabled" attribute');if("cut"===this.action&&(e.hasAttribute("readonly")||e.hasAttribute("disabled")))throw new Error('Invalid "target" attribute. You can\'t cut text from elements with "readonly" or "disabled" attributes');this._target=e}},get:function t(){return this._target}}]),t}();t.exports=c})},{select:5}],8:[function(e,n,o){!function(i,r){if("function"==typeof t&&t.amd)t(["module","./clipboard-action","tiny-emitter","good-listener"],r);else if(void 0!==o)r(n,e("./clipboard-action"),e("tiny-emitter"),e("good-listener"));else{var a={exports:{}};r(a,i.clipboardAction,i.tinyEmitter,i.goodListener),i.clipboard=a.exports}}(this,function(t,e,n,o){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function a(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function c(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function l(t,e){var n="data-clipboard-"+t;if(e.hasAttribute(n))return e.getAttribute(n)}var s=i(e),u=i(n),f=i(o),d="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},h=function(){function t(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}return function(e,n,o){return n&&t(e.prototype,n),o&&t(e,o),e}}(),p=function(t){function e(t,n){r(this,e);var o=a(this,(e.__proto__||Object.getPrototypeOf(e)).call(this));return o.resolveOptions(n),o.listenClick(t),o}return c(e,t),h(e,[{key:"resolveOptions",value:function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.action="function"==typeof e.action?e.action:this.defaultAction,this.target="function"==typeof e.target?e.target:this.defaultTarget,this.text="function"==typeof e.text?e.text:this.defaultText,this.container="object"===d(e.container)?e.container:document.body}},{key:"listenClick",value:function t(e){var n=this;this.listener=(0,f.default)(e,"click",function(t){return n.onClick(t)})}},{key:"onClick",value:function t(e){var n=e.delegateTarget||e.currentTarget;this.clipboardAction&&(this.clipboardAction=null),this.clipboardAction=new s.default({action:this.action(n),target:this.target(n),text:this.text(n),container:this.container,trigger:n,emitter:this})}},{key:"defaultAction",value:function t(e){return l("action",e)}},{key:"defaultTarget",value:function t(e){var n=l("target",e);if(n)return document.querySelector(n)}},{key:"defaultText",value:function t(e){return l("text",e)}},{key:"destroy",value:function t(){this.listener.destroy(),this.clipboardAction&&(this.clipboardAction.destroy(),this.clipboardAction=null)}}],[{key:"isSupported",value:function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:["copy","cut"],n="string"==typeof e?[e]:e,o=!!document.queryCommandSupported;return n.forEach(function(t){o=o&&!!document.queryCommandSupported(t)}),o}}]),e}(u.default);t.exports=p})},{"./clipboard-action":7,"good-listener":4,"tiny-emitter":6}]},{},[8])(8)});;

//$(document).ready(function () {

//    var clip = new ZeroClipboard($("#copy_button"));

//    clip.on("ready", function () {
//        //debugstr("Flash movie loaded and ready.");

//        this.on("aftercopy", function (event) {
//            //debugstr("Copied text to clipboard: " + event.data["text/plain"]);
//        });

//        clip.on("copy", function (event) {
//            // `this` === `client`
//            // `event.target` === the element that was clicked
//            //event.target.style.display = "none";

//            //console.log(event);
//            clip.setData("text/plain", oeditor.getValue());
//        });
//    });

//    clip.on("error", function (event) {
//        //debugstr('error[name="' + event.name + '"]: ' + event.message);
//        ZeroClipboard.destroy();
//    });

//});

$(document).ready(function () {


    var triggerId, clipId, type, ioType;
    if ($("#copy_editor").length > 0) {
        triggerId = "#copy_editor";
        clipId = $("#copy_editor");
        type = "E";
        ioType = clipId.data("editor");
    }
    else if ($("#copy_textarea").length > 0) {
        triggerId = "#copy_textarea";
        clipId = $("#copy_textarea");
        type = "T";
    }
    else
        return;


    var useZeroClipBoard = false;

    if (useZeroClipBoard) {

        var client = new ZeroClipboard();

        //client.clip(document.getElementById("copy_textarea"));
        client.clip(clipId);


        //client.setData("text/plain", editor.getValue());


        client.on("ready", function (readyEvent) {
            // alert( "ZeroClipboard SWF is ready!" );

            client.on("aftercopy", function (event) {
                // `this` === `client`
                // `event.target` === the element that was clicked
                //event.target.style.display = "none";

                //console.log(event);
                //alert("Copied text to clipboard: " + event.data["text/plain"]);
            });

            client.on("copy", function (event) {
                // `this` === `client`
                // `event.target` === the element that was clicked
                //event.target.style.display = "none";

                console.log(event);
                var content = getClipboardData();

                if (content != null && content.length > 0)
                    client.setData("text/plain", content);
            });

            //        client.on('mouseover', function(event) {
            //  clipId.tooltip('show');
            //});

        });

    }
    else {

        new Clipboard(triggerId, {
            text: function (trigger) {
                return getClipboardData();
            }
        });

        $(clipId).click(function () {
            var tt = $(this);

            tt.attr('data-original-title', 'copied!');
            //console.log(tt.attr('data-original-title'));

            //jQuery.noConflict();
            tt.tooltip("show");

            setTimeout(function () {
                tt.tooltip('hide');
                tt.attr('data-original-title', 'copy');
            }, 2000);
        });
    }


    function getClipboardData() {
        var content = "";
        if (type == "E") {
            content = (ioType === "I" ? iEditor.getValue() : oEditor.getValue());
        }
        else
            content = $("#newText").val();

        return content;
    }
});

     ;