var chk2;
var http_request = false;
var Gspacer=document.createTextNode(String.fromCharCode(160));
var appName = window.navigator.appName;

if(appName=='Netscape'){
    var	isff=true;
}else{
    var isff=false;
}

function resolution(){
    width=screen.width;

    if(width <= '800'){
        document.body.style.fontSize='11px';
    }

}

function inputover(element){
    element.background='#ffffff';
    element.color='#000000';
}

function inputout(element){
    element.background='#F3F3F3';
    element.color='#515151';
}

function display(id,toggle){
    // alert(id); return;
    if(toggle=='true'){

        if(document.getElementById(id).style.display=='block'){
            document.getElementById(id).style.display='none';
        }else{
            document.getElementById(id).style.display='block';
        }

    }else{
        document.getElementById(id).style.display='block';
    }

}

function closediv(id){
    document.getElementById(id).style.display='none';
}
counter=1;

function addfields(){

    if(counter>9){
        alert("limit: 10");
        return false;
    }
    counter++;

    var urldiv=document.createElement("div");
    urldiv.setAttribute("id","urlset"+counter);
    urldiv.style.paddingTop="10px";

    var hr=document.createElement('hr');
    urldiv.appendChild(hr);

    var table = document.createElement("table");
    table.setAttribute("border","0");
    table.cellSpacing="2";
    table.cellPadding="4";

    urldiv.appendChild(table);

    var tbody = document.createElement("tbody");
    table.appendChild(tbody);

    var tr=document.createElement("tr");
    tbody.appendChild(tr);

    var td2=document.createElement("td");
    td2.setAttribute("valign","top");
    td2.setAttribute("align","left");
    td2.setAttribute("width","62");
    tr.appendChild(td2);

    var span=document.createElement("label");
    // span.className='heading';
    span.setAttribute("for","url"+counter);
    td2.appendChild(span);

    var text = document.createTextNode("URL #"+counter+":");
    span.appendChild(text);

    var td3=document.createElement("td");
    td3.setAttribute("valign","top");
    td3.setAttribute("align","left");
    td3.setAttribute("width","");
    td3.setAttribute("height","40");
    tr.appendChild(td3);

    var input=document.createElement("input");
    input.type="text";
    input.name="url"+counter;
    input.id="url"+counter;
    input.className='urlInputtext';
    input.maxLength=400;
    td3.appendChild(input);

    var spacer=document.createTextNode(String.fromCharCode(160));
    td3.appendChild(spacer);

    var label=document.createElement("label");
    td3.appendChild(label);

    text=document.createTextNode(" Nudity or Adult URL?");
    label.appendChild(text);

    var urlAdult=document.createElement("input");
    urlAdult.type="checkbox";
    urlAdult.name="urlAdult"+counter;
    urlAdult.id="urlAdult"+counter;
    label.appendChild(urlAdult);

    spacer=document.createTextNode(" ");
    td3.appendChild(spacer);

    if(js_func.login=='true'){

        label=document.createElement("label");
        td3.appendChild(label);

        text=document.createTextNode(" Access ");
        label.appendChild(text);

        var access=document.createElement('select');
        access.setAttribute("name","access"+counter);
        access.setAttribute("id","access"+counter);

        var accessOption=document.createElement('option');
        accessOption.setAttribute("value","shared");

        var accessOptionText=document.createTextNode('Shared');
        accessOption.appendChild(accessOptionText);
        access.appendChild(accessOption);

        accessOption=document.createElement('option');
        accessOption.setAttribute("value","private");

        accessOptionText=document.createTextNode('Private');
        accessOption.appendChild(accessOptionText);
        access.appendChild(accessOption);

        label.appendChild(access);
    }

    spacer=document.createTextNode(String.fromCharCode(160));
    td3.appendChild(spacer);

    a1=document.createElement("a");
    a1.setAttribute("href","#");
    a1.className="more_link";
    eventAdder(a1,"onclick","display(this.parentNode.parentNode.parentNode.parentNode.parentNode.lastChild.previousSibling.id,'true');return false;");

    spacer=document.createTextNode(" ");
    td3.appendChild(spacer);

    td3.appendChild(a1);

    text=document.createTextNode("[Tags]");
    a1.appendChild(text);

    spacer=document.createTextNode(String.fromCharCode(160));
    td3.appendChild(spacer);

    spacer=document.createTextNode(String.fromCharCode(160));
    td3.appendChild(spacer);

    var a1=document.createElement("a");
    a1.setAttribute("href","#");
    a1.className="more_link";
    eventAdder(a1,"onclick","display(this.parentNode.parentNode.parentNode.parentNode.parentNode.lastChild.id,'true');return false;");
    td3.appendChild(a1);

    text=document.createTextNode("[Notes]");
    a1.appendChild(text);


    // next row for tags
    var div3=document.createElement("div");
    div3.setAttribute("id","saveTags"+counter);
    div3.style.display='none';
    urldiv.appendChild(div3);

    var table3=document.createElement("table");
    table3.setAttribute("border","0");
    table3.cellSpacing="2";
    table3.cellPadding="4";
    div3.appendChild(table3);

    var tbody3=document.createElement("tbody");
    table3.appendChild(tbody3);

    tr=document.createElement("tr");
    tbody3.appendChild(tr);

    td2=document.createElement("td");
    td2.setAttribute("valign","middle");
    td2.setAttribute("align","left");
    td2.setAttribute("width","62");
    tr.appendChild(td2);

    span=document.createElement("span");
    span.className='heading2';
    td2.appendChild(span);

    text = document.createTextNode("Tags #"+counter+":");
    span.appendChild(text);

    td3=document.createElement("td");
    td3.setAttribute("valign","middle");
    td3.setAttribute("align","left");
    td3.setAttribute("width","240");
    td3.setAttribute("height","40");
    tr.appendChild(td3);

    input=document.createElement("input");
    input.type="text";
    input.name="tags"+counter;
    input.id="tags"+counter;
    input.className='urlInputtext';
    input.maxLength=250;
    //    eventAdder(input,"onfocus","inputfocus(this.style,'')");
    //    eventAdder(input,"onblur","inputblur(this.style,'')");
    td3.appendChild(input);

    // end

    var div2=document.createElement("div");
    div2.setAttribute("id","moreinfo"+counter);
    div2.style.display='none';
    urldiv.appendChild(div2);

    var table2=document.createElement("table");
    table2.setAttribute("border","0");
    table2.cellSpacing="2";
    table2.cellPadding="4";
    div2.appendChild(table2);

    var tbody2=document.createElement("tbody");
    table2.appendChild(tbody2);

    tr=document.createElement("tr");
    tbody2.appendChild(tr);

    td2=document.createElement("td");
    td2.setAttribute("valign","middle");
    td2.setAttribute("align","left");
    td2.setAttribute("width","62");
    tr.appendChild(td2);

    span=document.createElement("span");
    span.className='heading2';
    td2.appendChild(span);

    text = document.createTextNode("Notes #"+counter+":");
    span.appendChild(text);

    td3=document.createElement("td");
    td3.setAttribute("valign","middle");
    td3.setAttribute("align","left");
    td3.setAttribute("width","310");
    td3.setAttribute("height","82");
    tr.appendChild(td3);

    var textarea=document.createElement("textarea");
    textarea.name="notes"+counter;
    textarea.id="notes"+counter;

    td3.appendChild(textarea);


    var insertHere = document.getElementById('writeroot');
    insertHere.parentNode.insertBefore(urldiv,insertHere);
    document.urlsaveform.counter.value=counter;

    if(counter>1){
        //        document.getElementById('groupurl').style.display='block';
        document.getElementById('removeBtn').style.display='inline';
    }

    $.ajax({
        type: "POST",
        url: js_func.rootPath+"ajax_request.php",
        data: "func=loadTags",

        success: function(msg){
            $.tagArray=msg.split(' ');

            $("#tags"+counter).autocomplete($.tagArray, {
                width: 320,
                max: 500,
                highlight: false,
                multiple: true,
                multipleSeparator: " ",
                scroll: true,
                scrollHeight: 300
            });
        }
    });

    $('#notes'+counter).jqEasyCounter({
        'maxChars': 500,
        'maxCharsWarning': 490,
        'msgFontSize': '11px',
        'msgFontColor': '#000',
        'msgTextAlign': 'right',
        'msgWarningColor': '#F00',
        'msgAppendMethod': 'insertAfter'
    });

    var removeBtn=document.getElementById('removeBtn');

    removeBtn.onclick=function(){
        // alert(counter);
        var urlSet=document.getElementById('urlset'+counter);
        urlSet.parentNode.removeChild(urlSet);
        counter--;
        document.urlsaveform.counter.value=counter;

        if(counter<2){
            document.getElementById('removeBtn').style.display='none';
        }
    }
    return true;
}

function username_focus(){

    if(document.loginform){

        if(document.loginform.username.value==''){
            document.loginform.username.focus();
        }
        else{
            document.loginform.password.focus();
        }
    }
}

function removenode(node){
    alert(node);
    return;
    counter=document.urlsaveform.counter.value;
    counter--;

    if(counter<2){
        document.getElementById('groupurl').style.display='none';
    }
    document.urlsaveform.counter.value=counter;
    node.parentNode.removeChild(node);
}

function removeURLDiv(){
    counter=document.urlsaveform.counter.value;
    urlSet=document.getElementById('urlset'+counter);

    if(counter<2){
        document.getElementById('groupurl').style.display='none';
    }
    document.urlsaveform.counter.value=counter;
    node.parentNode.removeChild(node);
}

function mytags(){
    hfwidth=screen.width/2;
    hfheight=screen.height/2;
    width=screen.width;
    height=screen.height;
    document.getElementById('mytags').style.display='block';
    document.getElementById('mytags').style.width=hfwidth+'px';
    document.getElementById('mytags').style.height=hfheight+20+'px';
    document.getElementById('mytags').style.left=screen.height/3+'px';
    document.getElementById('tagsdisp').style.height=hfheight-30+'px';
}

function eventAdder(objAttrib,handler,addFunction){

    if ((!document.all)&&(document.getElementById)){
        objAttrib.setAttribute(handler,addFunction);
    }
    // workaround for IE 5.x
    if ((document.all)&&(document.getElementById)){
        objAttrib[handler]=new Function(addFunction);
    }

}

counter=1;

function checked(id,tag){
    var chk=document.getElementById('chkbx'+id);
    chk.checked=!chk.checked;
    var sel=document.getElementById('selected');
    td=chk.parentNode;

    if(chk.checked==true){
        td.style.background='#17A8FF';
        // alert(counter);
        if(counter>=2){
            sel.innerHTML+=", ";
        }
        sel.innerHTML+=tag;
        counter++;
    }

    if(chk.checked==false){
        td.style.background='#B3E2FF';
        sel.innerHTML-=tag;
    }

}

function urlsave_submit(formn,button){
    $("div#urlsave input").removeClass('error');
    $("div#urlsave textarea").removeClass('error');
    var form=eval('document.'+formn);
    var counter=form.counter.value;
    var groupname=form.groupname.value;
    var groupNameNew=(form.groupNameNew)?form.groupNameNew.value:'';

    var urlstr='';
    var notestr='';
    var tagstr='';
    var urlAdultstr='';
    var urlAccessStr='';

    for(i=1;i<=counter;i++){
        var url_val=document.getElementById('url'+i).value;
        urlstr = urlstr+"&url"+i+"="+Base64.encode(url_val);

        var note_val=escape(document.getElementById('notes'+i).value);
        notestr = notestr+"&notes"+i+"="+note_val;

        var tag_val=escape(document.getElementById('tags'+i).value);
        tagstr = tagstr+"&tags"+i+"="+tag_val;

        var urlAdult_val=escape(document.getElementById('urlAdult'+i).checked);
        urlAdultstr = urlAdultstr+"&urlAdult"+i+"="+urlAdult_val;

        if(js_func.login=='true'){
            var urlAccess_val=escape(document.getElementById('access'+i).value);
            urlAccessStr = urlAccessStr+"&urlAccess"+i+"="+urlAccess_val;
        }

    }
    var guest='';

    if(js_func.login=='true'){
        guest="false";
    }else{
        guest="true";
    }

    var params = urlAccessStr+urlAdultstr+tagstr+urlstr+notestr+"&counter="+counter+"&groupname="+groupname+"&groupNameNew="+groupNameNew+"&guest="+guest+"&func=urlchk&rand="+calcRand();
    button.disabled=true;
    form.add_more_button.disabled=true;
    form.removeBtn.disabled=true;

    var myRequest = new ajaxObject('/ajax_request.php',urlsaveResponse,"1");
    myRequest.update(params,'post');

    return false;
}

function trim(text) {
    return text.replace(/^\s+|\s+$/g,"");
}

function calcRand() {
    date=new Date().getTime();
    retVal = Math.floor(Math.random() * 1001);
    retVal += Math.floor(Math.random() * date);
    return retVal;
}

function form_submit(formn,button){

    // alert(form.protype.value)
    form=eval('document.'+formn);

    if(form.username.value==''){
        alert('Please provide, Username');
        return;
    }

    if(form.userchk.value==''){
        checkusername(form.username.value);
    }

    if(form.userchk.value=='ok'){
        var chk1=performCheck(formn, rules, 'classic');

        if(chk1==true){

            if(form.emailchk.value==''){
                checkemail(form.email.value);
            }

            if(form.emailchk.value=='ok'){
                button.disabled='disabled';
                form.submit();
            }
        }
    }
}

function getPageSize2(){
    var xScroll;
    var yScroll;

    if (window.innerHeight && window.scrollMaxY) {
        xScroll = window.innerWidth + window.scrollMaxX;
        yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all
        // but
        // Explorer
        // Mac
        xScroll = document.body.scrollWidth;
        yScroll = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla
        // and
        // Safari
        xScroll = document.body.offsetWidth;
        yScroll = document.body.offsetHeight;
    }
    var windowWidth, windowHeight;
    // console.log(self.innerWidth);
    // console.log(document.documentElement.clientWidth);
    if (self.innerHeight) {	// all except Explorer
        if(document.documentElement.clientWidth){
            windowWidth = document.documentElement.clientWidth;
        } else {
            windowWidth = self.innerWidth;
        }
        windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer
        // 6
        // Strict
        // Mode
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
    }
    // for small pages with total height less then height of the viewport
    if(yScroll < windowHeight){
        pageHeight = windowHeight;
    } else {
        pageHeight = yScroll;
    }
    // console.log("xScroll " + xScroll)
    // console.log("windowWidth " + windowWidth)
    // for small pages with total width less then width of the viewport
    if(xScroll < windowWidth){
        pageWidth = xScroll;
    } else {
        pageWidth = windowWidth;
    }
    // console.log("pageWidth " + pageWidth)
    arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
    return arrayPageSize;
}

function showupload(){
    var objBody = document.getElementsByTagName("body").item(0);
    var objOverlay = document.createElement("div");
    objOverlay.setAttribute('id','overlay1');
    objOverlay.style.display = 'block';
    objBody.appendChild(objOverlay);
    var arrayPageSize = getPageSize2();
    Element.setWidth('overlay1', arrayPageSize[0]);
    Element.setHeight('overlay1', arrayPageSize[1]);
    document.getElementById('uploadbox').style.display='block';
}

function hideupload(){
    document.getElementById('overlay1').style.display='none';
    document.getElementById('uploadbox').style.display='none';
    node=document.getElementById('overlay1');
    node.parentNode.removeChild(node);
}

function uploadavtar(var1){
    var2=var1.split(".");
    len=var2.length;
    ext=var2[len-1];
    allow=new Array("gif","jpg","jpeg","png","GIF","JPG","JPEG","PNG");
    var3='';
    for(i=0;i<allow.length;i++){
        if(allow[i]==ext){
            var3=true;
        }

    }

    if(var3==true){
        document.avtarform.submit();
    }else{
        document.getElementById('status').innerHTML='Invalid file type';
    }

}

function checkurl(theUrl){
    if(theUrl.match(/^([\.\-]\w+)*\.\w{2,4}(\:\d+)*([\/\.\-\?\&\%\#]\w+)*\/?$/i)){
        return 'right';
    } else {
        return 'wrong';
    }
}

function urlsaveResponse(response){
    // alert(response);return;
    var reason='';
    var status='';
    var url='';
    var redirect=true;

    document.getElementById('save_status').style.display='block';
    var arr1=response.split("~");
    var count1=arr1.length;
    var html_disp="<ul>";
    var arr2;

    for(i=0;i<count1;i++){
        arr2=arr1[i].split("#");

        if(arr1[i]!=''){
            html_disp=html_disp+"<li>";

            if(arr2[2]=="saved"){
                reason="Successfully saved!";
            }else if(arr2[2]=="exist"){
                redirect=false;
                reason="Already Exist !";
            }else if(arr2[2]=="invalid"){
                redirect=false;
                reason="its Invalid URL";
            }else if(arr2[2]=="notes_limit_exceed"){
                redirect=false;
            }else if(arr2[2]=="tags_limit_exceed"){
                redirect=false;
            }

            if(arr2[0]=='true'){
                status="<span style='color:#12AF16;'><em>URL #"+arr2[1]+reason+"</em></span>";
            }else if(arr2[2]=="exist"){
                status="<span style='color:#B64B0C;'><em>URL #"+arr2[1]+" "+reason+"</em></span>";
            }else if(arr2[2]=="invalid"){
                status="<span style='color:#ff0000;'><em>Error while saving URL #"+arr2[1]+" because "+reason+"</em></span>";
            }else if(arr2[2]=="notes_limit_exceed"){
                status="<span style='color:#ff0000;'><em>For URL #"+arr2[1]+" notes limit exceeded (max: 500 characters allowed).</em></span>";
                $('#notes'+arr2[1]).addClass('error');
            }else if(arr2[2]=="tags_limit_exceed"){
                status="<span style='color:#ff0000;'><em>For URL #"+arr2[1]+" tags limit exceeded (max: 300 characters allowed).</em></span>";
                $('#tags'+arr2[1]).addClass('error');
            }
            html_disp=html_disp+status;
            html_disp=html_disp+"</li>";
        }
    }

    if(redirect==true){
        (js_func.login=='true')?url="my-saved-url":url="shared-url";
        window.location.href=js_func.rootPath+url;
        return;
    }
    var linkText='';

    if(js_func.login=='true'){
        linkText="<a href='/my-saved-url'>Go to my saved URL</a>";
    }else{
        linkText="<a href='/shared-url'>Go to shared URL</a>";
    }
    html_disp=html_disp+"</ul>";
    html_disp=html_disp+"&nbsp;&nbsp;<a href='#' onclick='reset_form();return false;'>Reset form</a> | "+linkText;
    document.getElementById('save_status').innerHTML=html_disp;

    $('#save_all_button').removeAttr('disabled');
    $('#add_more_button').removeAttr('disabled');
    $('#removeBtn').removeAttr('disabled');
}

function checkusername(username) {
    // alert(username);
    var params = "&username="+username+"&func=checkUser&rand="+calcRand();
    var myRequest = new ajaxObject('ajaxSiteRequest.php',usrchk_response);
    myRequest.update(params,'post');
}

function usrchk_response(response){
    // alert(response);
    username=document.joinusform.username.value;
    check=document.joinusform.userchk;

    if(response=='true'){
        // alert('sarav');
        document.getElementById('notavailable').style.display='none';
        document.getElementById('available').style.display='block';
        document.getElementById('available').innerHTML=username+" is available!";
        check.value='ok';
    }
    else{
        document.getElementById('available').style.display='none';
        document.getElementById('notavailable').style.display='block';
        document.getElementById('notavailable').innerHTML=response;
        check.value='';
    }
}

function checkemail(email) {
    var params = "&email="+email+"&func=checkEmail&rand="+calcRand();
    var myRequest = new ajaxObject('ajaxSiteRequest.php',emailchk_response);
    myRequest.update(params,'post');
}

function emailchk_response(response){
    // alert(response);
    email=document.joinusform.email.value;
    check=document.joinusform.emailchk;

    if(response==''){
        document.getElementById('email_true').style.display='none';
        document.getElementById('email_false').style.display='none';
        check.value='ok';
    }else{
        document.getElementById('email_true').style.display='none';
        document.getElementById('email_false').style.display='block';
        document.getElementById('email_false').innerHTML=response;
        check.value='';
    }
}

function reset_form(){
    form=document.urlsaveform;
    var counter=form.counter.value;// ------------passing the same counter
    // value for ie----------------
    form.reset();
    form.counter.value=counter;

    form.save_all_button.disabled=false;
    form.add_more_button.disabled=false;
    form.removeBtn.disabled=false;

    //    form.group.checked=false;
    $('#url1').focus();
    $('#save_status').hide();
    $('#groupname').hide();
}

function url_description(desc,id){
    var div=document.getElementById(id);
    len=desc.length;

    if(len>600){
        s_desc=desc.substr(0,600);
        arr=s_desc.split(" ");
        var str='';

        for(var i=0;i<arr.length;i++){

            if(i!=arr.length-1){
                str=str+" "+arr[i];
            }
        }
        str=str+" ...";
        div.innerHTML=str;
    }
    else{
        div.innerHTML=desc;
    }
}

function show_border(id){
    var div=document.getElementById(id);
    div.style.border='1px solid #FFA4A4';
}

function hide_border(id){
    var div=document.getElementById(id);
    div.style.border='1px solid #ffffff';
}



function ajaxObject(url, callbackFunction, mes) {
    var that=this;
    this.updating = false;

    this.abort = function() {
        if (that.updating) {
            that.updating=false;
            that.AJAX.abort();
            that.AJAX=null;
        }
    }

    this.update = function(passData,postMethod) {
        if (that.updating) {
            return false;
        }
        that.AJAX = null;
        if (window.XMLHttpRequest) {
            that.AJAX=new XMLHttpRequest();
        } else {
            that.AJAX=new ActiveXObject("Microsoft.XMLHTTP");
        }
        if (that.AJAX==null) {
            return false;
        } else {
            that.AJAX.onreadystatechange = function() {
                if (that.AJAX.readyState==4) {

                    js_func.hideProcessing();

                    that.updating=false;
                    that.callback(that.AJAX.responseText,that.AJAX.status,that.AJAX.responseXML);
                    that.AJAX=null;
                }
            }

            that.updating = new Date();

            js_func.show_processing(mes);

            if (/post/i.test(postMethod)) {
                var uri=urlCall+'?'+that.updating.getTime();
                that.AJAX.open("POST", uri, true);
                that.AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                that.AJAX.setRequestHeader("Content-Length", passData.length);
                that.AJAX.send(passData);
            } else {
                var uri=urlCall+'?'+passData+'&timestamp='+(that.updating.getTime());
                that.AJAX.open("GET", uri, true);
                that.AJAX.send(null);
            }
            return true;
        }
    }

    var urlCall = url;
    this.callback = callbackFunction || function () { };
}

