/**
*
*    JavaScript Invitation editor for 123invitation.dk
*
* @AUTHOR: Jan-Erik Revsbech <jer@mocsystems.dk>
*
*
*/

var currentPage=0;
var editor_uid= 5; //The uid of the invitation editor.
var currentworkareacmd = 'none'; //The current state of the vorkarea.
var invitationuid=0;
var currenttemplate = ''; //Used for the template selector, contain the key of the currently chosen template.
var enabledfeatures = 0;
var editor=null; //The Dojo RTE.
var editor_num = 0;
var win_popup;
var language=28; //Uid of static_languages record
dojo.require("dojo.io.*");
dojo.require("dojo.io.IframeIO");
//  dojo.require("dojo.widget.Editor");
var headercolor;



function openPopup(url) {
  //win_popup = window.open(url,'popupwin','width=700,height=540');
  win_popup = window.open(url,'popupwin','resizable=0,location=0,status=0,scrollbars=1,width=700,height=540');

  if(win_popup) {
    win_popup.focus();
  } else {
  }

}

function payOnAccount(url,error) {
    var num_months = document.getElementById('num_months').value;
    var num_images = document.getElementById('num_images').value;
    if(num_months==0 && num_images==0) {
        alert(error);
        return;
    }
    url = url +"&num_months="+num_months+"&num_images="+num_images;
    document.location.href=url;


}
function paymentPopup(url,error) {
    var num_months = document.getElementById('num_months').value;
    var num_images = document.getElementById('num_images').value;
	//if(document.getElementById('currency')) {
    var currency = document.getElementById('currency').value;
    var paymentmethod = document.getElementById('paymentmethod').value;

    if(num_months==0 && num_images==0) {
        alert(error);
        return;
    }

    //alert("Method: "+paymentmethod);

    //total = num_months*monthprice+num_images*imagesprice;
    url = url +"&currency="+currency+"&num_months="+num_months+"&num_images="+num_images+"&paymethod="+paymentmethod;
    //alert("Opening payment data in new window. ToDO: Validate form:" +url);
//    openPopup('https://betaling.wannafind.dk/proxy/p.php/'+url);
    openPopup('https://betaling.curanet.dk/secureproxy/proxy.php/'+url);
}

function setEditPage(uid) {
    editor_uid=uid;
}
function setLanguage(lang) {
    language=lang;
}

function updateInvitationColor(key,newcol) {
    //alert("Changing color "+key+" to "+newcol);
    updateWorkArea('changeinvitationcolors','&key='+key+'&newcolor='+escape(newcol),true);
}

function updateHeaderColor(newcol) {
    handle= document.getElementById('headercol_'+newcol);
    if(handle != null) {
        //alert("Setteing active on "+newcol);
        handle.className="colorActive";
    }
    oldhandle = document.getElementById('headercol_'+headercolor);
    if(oldhandle != null) {
        oldhandle.className="colorNormal";
    }
    headercolor=newcol;
    document.getElementById('headercolor').value=newcol;
}
function setInvitationUid(uid) {
    invitationuid=uid;
}
function setEnabledFeatures(feat) {
//alert("New: "+feat);
    enabledfeatures = feat;
}

function typolink(uid,origLink) {
    currentPage = uid;

    do_cancel();


    //Check if there is already a question mark (RealURL compatible)
    if(origLink.indexOf('?')>0) {
        url = origLink+'&ACTIVATE_INVITATION_EDITOR=1&123LANG='+language+'&no_cache=1';
    } else {
        url = origLink+'?ACTIVATE_INVITATION_EDITOR=1&123LANG='+language+'&no_cache=1';
    }
    //alert("Url: "+url);

    document.getElementById('previewframe').src=url;
}
/**
*
*/
function deleteGuest(uid) {
    updateWorkArea('deleteguest','&guest_uid='+uid,true);
    //updatePreview();
}
/**
*
*/
function signupGuest(uid) {
    updateWorkArea('signupguest','&guest_uid='+uid);
    updatePreview();
}
/**
*
*/
function addGuestsToGuestList() {
  updateWorkArea('addguests');
}
/**
*
*/
function chooseFeatures() {
    updateWorkArea('choosefeatures','');
    closeShortcutMenu();
}

/**
*
*/
function toggleFeature(feature_nr) {
    key = Math.pow(2,feature_nr);

    //alert("Before: "+enabledfeatures);
    if((enabledfeatures&key) == key) {
        document.getElementById('featureimage_'+feature_nr).src='typo3conf/ext/123/res/images/flueben_grey_v2.gif';
        temp = 255^key;
        //alert("Temp: "+temp);
        enabledfeatures = temp&enabledfeatures;
    } else {
        //alert("Enabling feature "+feature_nr);
        document.getElementById('featureimage_'+feature_nr).src='typo3conf/ext/123/res/images/flueben_green_v2.gif';
        enabledfeatures = enabledfeatures|key;

    }
    //alert("After: "+enabledfeatures);
}
/**
*
*/
function saveFeatures() {
    //alert("Saving features bit: "+enabledfeatures+" to dB");
    updateWorkArea('changefeatures','&features_bit='+enabledfeatures);
    updatePreview();
}
/**
*
*/
function saveGuestlistAddition() {
//    alert("Request to upload image on page: "+page);
    var dojoUrl = 'index.php?id='+editor_uid+'&type=58&invitation='+invitationuid+'&cmd=addguests';
    //dojo.require("dojo.io.IframeIO");
     dojo.io.bind({
        url: dojoUrl,
        load: function(type, data, evt) {
          document.getElementById('workarea_content').innerHTML = data;
          updatePreview();
        },
        mimetype: "text/plain",
        encoding: "utf-8",
        transport: "XMLHTTPTransport",
        formNode: document.getElementById("add_guests_form")
        });
    }

/**
*
*/
function savePageTitles() {
    var dojoUrl = 'index.php?id='+editor_uid+'&type=58&invitation='+invitationuid+'&cmd=changepagetitles';
    //dojo.require("dojo.io.IframeIO");
     dojo.io.bind({
        url: dojoUrl,
        load: function(type, data, evt) {
          document.getElementById('workarea_content').innerHTML = data;
          updatePreview();
        },
        mimetype: "text/plain",
        encoding: "utf-8",
        transport: "XMLHTTPTransport",
        formNode: document.getElementById("changepagetitles_form")
        });

}

/**
*
*/
function editText(uid) {
    //alert("Editing textelement: "+uid);
    //updateWorkArea('edittextelement','&record_uid='+uid);
    //var editor = dojo.widget.fromScript("Editor", {}, dojo.byId("textEditor"));
  var dojoUrl = 'index.php?id='+editor_uid+'&type=58&invitation='+invitationuid+'&cmd=edittextelement&record_uid='+uid+'&editornum='+editor_num;
  currentworkareacmd = 'edittextelement';

 dojo.io.bind({
    url: dojoUrl,
    load: function(type, data, evt) {
        //I internet explorer er dette nødvendigt for at få RTE'en til at virke.
      clearWorkArea();
      document.getElementById('workarea_content').innerHTML = data;
            editor = new FCKeditor( 'texteditor');

            editor.BasePath = "typo3conf/ext/123/lib/FCKeditor/" ;
            editor.Width = 225 ;
            editor.Height = 400 ;
            editor.ToolbarSet = 'invitation' ;
            editor.ReplaceTextarea();
    },
    mimetype: "text/plain",
    encoding: "utf-8",
    transport: "XMLHTTPTransport"
    });
}
/**
*
*/
function changeTitle(uid) {
 var dojoUrl = 'index.php?id='+editor_uid+'&type=58&invitation='+invitationuid+'&cmd=changetitle&page_uid='+uid;
 dojo.io.bind({
    url: dojoUrl,
    load: function(type, data, evt) {
      document.getElementById('workarea_content').innerHTML = data;
      updatePreview();
      updateHeaderColor(document.getElementById('headercolor').value);

    },
    mimetype: "text/plain",
    encoding: "utf-8",
    transport: "XMLHTTPTransport",
    formNode: document.getElementById("change_title_form")
    });
}
/**
*
*/
function editImage(uid,cat) {
    //alert("Editing textelement: "+uid+"");
    if(cat!=null) {
        updateWorkArea('editimage','&page_uid='+uid+'&img_cat='+cat);
    } else {
        updateWorkArea('editimage','&page_uid='+uid);
    }
}
/**
*
*/
function editImageHeader(uid) {

 var dojoUrl = 'index.php?id='+editor_uid+'&type=58&invitation='+invitationuid+'&cmd=editimageheader&page_uid='+uid;
 dojo.io.bind({
    url: dojoUrl,
    load: function(type, data, evt) {
      document.getElementById('workarea_content').innerHTML = data;
      updateHeaderColor(document.getElementById('headercolor').value);
    },
    mimetype: "text/plain",
    encoding: "utf-8",
    transport: "XMLHTTPTransport"
    });
}
/**
*
*/
function saveImage(page,newimage,catdir) {
    //alert("Changing image on page"+page+" to image: "+newimage);
    var dojoUrl = 'index.php?id='+editor_uid+'&type=58&invitation='+invitationuid+'&cmd=saveimage&page_uid='+page+'&newimage='+newimage+'&cat_dir='+catdir;
    dojo.io.bind({
    url: dojoUrl,
    load: function(type, data, evt) {
      document.getElementById('workarea_content').innerHTML = data;
      updatePreview();
    },
    mimetype: "text/plain",
    encoding: "utf-8"
    });
}
/**
*
*/
function saveDefaultImage(newimage) {
    //alert("Changing image on page"+page+" to image: "+newimage);
    var dojoUrl = 'index.php?id='+editor_uid+'&type=58&invitation='+invitationuid+'&cmd=savedefaultimage&newimage='+newimage;
    dojo.io.bind({
    url: dojoUrl,
    load: function(type, data, evt) {
      document.getElementById('workarea_content').innerHTML = data;
      updatePreview();
    },
    mimetype: "text/plain",
    encoding: "utf-8"
    });
}
/**
*
*/
function saveExampleOptions() {
 var dojoUrl = 'index.php?id='+editor_uid+'&type=58&invitation='+invitationuid+'&cmd=changeexampleoptions';
     dojo.io.IframeTransport.setUpIframe();

 dojo.io.bind({
    url: dojoUrl,
    load: function(type, data, evt) {
      document.getElementById('workarea_content').innerHTML = data;
      //updatePreview();
    },
    mimetype: "text/plain",
    encoding: "utf-8",
    formNode: document.getElementById("exampleoptions_form")
    });
}
/**
*
*/
function saveTemplateOptions() {
 var dojoUrl = 'index.php?id='+editor_uid+'&type=58&invitation='+invitationuid+'&cmd=changetemplateoptions';
     dojo.io.IframeTransport.setUpIframe();

 dojo.io.bind({
    url: dojoUrl,
    load: function(type, data, evt) {
      document.getElementById('workarea_content').innerHTML = data.body.innerHTML;
      updatePreview();
    },
    mimetype: "text/xml",
    encoding: "utf-8",
    formNode: document.getElementById("templateoptions_form")
    });
}
//templateoptions_form
/**
*
*/
function clearImage(page) {
    //alert("Changing image on page"+page+" to image: "+newimage);
    var dojoUrl = 'index.php?id='+editor_uid+'&type=58&invitation='+invitationuid+'&cmd=clearimage&page_uid='+page;
    dojo.io.bind({
    url: dojoUrl,
    load: function(type, data, evt) {
      document.getElementById('workarea_content').innerHTML = data;
      updatePreview();
    },
    mimetype: "text/plain",
    encoding: "utf-8"
    });
}
/**
*
*/
function uploadFiles(uid) {
//    alert("Request to upload image on page: "+page);
    var dojoUrl = 'index.php?id='+editor_uid+'&type=58&invitation='+invitationuid+'&cmd=uploadfiles&element='+uid;
    dojo.require("dojo.io.IframeIO");
    dojo.io.IframeTransport.setUpIframe();
    dojo.io.bind({
        url: dojoUrl,
        load: function(type, data, evt) {
          document.getElementById('workarea_content').innerHTML = data.body.innerHTML;
          updatePreview();
        },
        mimetype: "text/xml",
        encoding: "utf-8",
        formNode: document.getElementById("upload_files_form")
    });
}
/**
*
*/
function uploadImage(page) {
//    alert("Request to upload image on page: "+page);
    var dojoUrl = 'index.php?id='+editor_uid+'&type=58&invitation='+invitationuid+'&cmd=uploadimage&page_uid='+page;
    //dojo.require("dojo.io.IframeIO");
    dojo.io.IframeTransport.setUpIframe();
    dojo.io.bind({
        url: dojoUrl,
        load: function(type, data, evt) {
          document.getElementById('workarea_content').innerHTML = data.body.innerHTML;
          //updatePreview();
        },
        mimetype: "text/xml",
        encoding: "utf-8",
        formNode: document.getElementById("upload_image_form")
    });
}
/**
*
*/
function uploadCompanyLogo() {
//    alert("Request to upload image on page: "+page);
    var dojoUrl = 'index.php?id='+editor_uid+'&type=58&invitation='+invitationuid+'&cmd=uploadcompanylogo';
        dojo.io.IframeTransport.setUpIframe();

    dojo.io.bind({
    url: dojoUrl,
    load: function(type, data, evt) {
      document.getElementById('workarea_content').innerHTML = data.body.innerHTML;
      updatePreview();
    },
    mimetype: "text/xml",
    encoding: "utf-8",
    formNode: document.getElementById("upload_companylogo_form")
    });
}
/**
*
*/
function deleteImage(page,image) {
    updateWorkArea('delimage','&page_uid='+page+'&image='+image);
}
/**
*
*/
function saveContentElement(uid) {
 var dojoUrl = 'index.php?id='+editor_uid+'&type=58&invitation='+invitationuid+'&cmd=savecontentelement&record_uid='+uid;
 var oEditor = FCKeditorAPI.GetInstance('texteditor');
 //alert("Test: "+oEditor.GetXHTML());
 //oEditor.UpdateLinkedField();

 dojo.io.bind({
    url: dojoUrl,
    content: {
//        "data[bodytext]": editor.getEditorContent()
        "data[bodytext]": oEditor.GetXHTML()
    },
    load: function(type, data, evt) {

      clearWorkArea();
      document.getElementById('workarea_content').innerHTML = data;

      updatePreview();
      //editor_num=editor_num+1;
      delete editor;
      editor = null;
    },
    mimetype: "text/plain",
    encoding: "utf-8",
    transport: "XMLHTTPTransport",
    formNode: document.getElementById("texteditor_form")
    });
}

/**
* this function resets the workArea to the def. value.
*/
function do_cancel() {
    //alert("Canceling: "+currentworkareacmd);
//    updateWorkArea('none','');
    //document.getElementById('workarea_content').innerHTML = 'Workarea';
    clearWorkArea();
    currentworkareacmd = 'none';
}

/**
*
*/
function updatePreview() {
    var handle = document.getElementById('previewframe');
    if(handle != null) {
        //alert("REfresh");
        oldurl = handle.src;
        d= new Date().getTime();
        if(oldurl.indexOf('&notused=')>0) {
            newurl = oldurl.replace(/&notused=.*/,'&notuser='+d);
        } else {
            newurl = oldurl + "&notused="+d;
        }

        //alert ("oldurl: "+oldurl+" Newurl: "+newurl);
        handle.src = newurl;

        /*
        doc = getIframeContentDocument(handle);
        if(doc) {
            document.getElementById('previewframe_blurobject').style.visibility = "visible";
            doc.onload = previewLoaded();
        }
        //handle.contentDocument.onload = function() {alert('test');};
        //handle.contentDocument.onload = previewLoaded();
        */
    }
}

/**
*
*/
function getIframeContentDocument(iframe_el){
  var doc = iframe_el.contentDocument || // W3
    (
      (iframe_el.contentWindow)&&(iframe_el.contentWindow.document)
    ) ||  // IE
    (
      (iframe_el.name)&&(document.frames[iframe_el.name])&&
      (document.frames[iframe_el.name].document)
    ) || null;
  return doc;
}

/**
*
*/
function previewLoaded() {
    //alert("Preview finished loading");
    //document.getElementById('previewframe_blurobject').style.visibility = "hidden";
}
/**
*   I internet explorere ser det ud til at være vigtigt at Workarea cleares før man indsætter nyt indhol. Kræver DOM 1.0...
*/
function clearWorkArea() {
    temp = document.getElementById('workarea_content');
    for(i=0;i<temp.childNodes.length;i++) {
      temp.removeChild(temp.childNodes[i]);
    }
    temp.innerHTML = '';
}
/**
*
*/
function updateWorkArea(cmd,addParams,refreshPreview) {
  //closeShortcutMenu();
  if(addParams != null) {
    var dojoUrl = 'index.php?id='+editor_uid+'&type=58&invitation='+invitationuid+'&cmd='+cmd+addParams;
  } else {
    var dojoUrl = 'index.php?id='+editor_uid+'&type=58&invitation='+invitationuid+'&cmd='+cmd;
  }
  currentworkareacmd = cmd;

 dojo.io.bind({
    url: dojoUrl,
    load: function(type, data, evt) {
      //alert("Data: "+data);
      document.getElementById('workarea_content').innerHTML = data;
      if(refreshPreview != null) {
        updatePreview();
      }
      //alert("Setting history "+col+":"+cmd+" to "+data);
      //dhtmlHistory.add(col+":"+cmd,data);
    },
    mimetype: "text/plain",
    encoding: "utf-8",
    transport: "XMLHTTPTransport"
    });
}
/**
*
*/
function toggleShortcutMenu() {
    handle = document.getElementById('shortcut_container');
    if(handle.style.visibility == "hidden") {
        handle.style.visibility = "visible";
    } else {
        handle.style.visibility = "hidden";
    }
}
/**
*
*/
function closeShortcutMenu() {
    /*
    handle = document.getElementById('shortcut_container');
    handle.style.visibility = "hidden";
    */
    //Since there is no shortcutmenu, just do nothing.
}
/**
*
*/
function togglePreviewBlur() {
    handle = document.getElementById('previewframe_blurobject');
    if(handle.style.visibility == "hidden") {
        handle.style.visibility = "visible";
    } else {
        handle.style.visibility = "hidden";
    }
}

/**
*
*/
function changeTemplatePreview(template) {
  // handle = document.getElementById('template_selector_image');
  // handle.innerHTML = 'Test: '+template;
 //alert("ChangeTemplatePreview "+template);
 currenttemplate=template;
 var dojoUrl = 'index.php?id='+editor_uid+'&type=58&invitation='+invitationuid+'&cmd=previewtemplate&template='+template;
 dojo.io.bind({
    url: dojoUrl,
    load: function(type, data, evt) {
      document.getElementById('template_selector_image').innerHTML = data;
      //updatePreview();
    },
    mimetype: "text/plain",
    encoding: "utf-8"
    });
}
/**
*
*/
function saveChosenTemplate(notmpl_error) {
    if(currenttemplate=="") {
        alert(notmpl_error);
    } else {
        alert("Setting template to: "+currenttemplate);
    }
}

/* ************************** PAYMENT FUNCTIONS **************************** */
//ToDo: Make setPricesFunction and setVatPercentage

//var vat = 0.25;
//var monthprice = 39;
//var imagesprice = 1;
//var	currency_decimal_digits = 2;
//var	currency_thousands_point = '.';
//var	currency_decimal_point = ',';


function setVat(ratio) {
	vat = ratio
}
function setMonthPrice(price) {
	monthprice = price;
}
function setImagesPrice(price) {
	imagesprice = price;
}
function setCurrencyFormat(decimal_digits,thousands_point,decimal_point,iso_code) {
	currency_decimal_digits = decimal_digits;
	currency_thousands_point = thousands_point;
	currency_decimal_point = decimal_point;
	currency_iso_code = iso_code;
}
function formatCurrency(amount) {
	return amount.toFixed(currency_decimal_digits).replace(currency_thousands_point,currency_decimal_point);
}
function changeNumMonths(newval) {
    newlineprice = newval*monthprice;
    //lineprices[0]=newlineprice;
    document.getElementById('month_total').innerHTML = formatCurrency(newlineprice);
//newlineprice.toFixed(2).replace('.',',');
    changeTotalPrice();
}
function changeNumImages(newval) {

    newlineprice = newval*imagesprice;
    //lineprices[1]=newlineprice;
    document.getElementById('images_total').innerHTML = formatCurrency(newlineprice);
    changeTotalPrice();
}
function updateCurrency() {
	var currency_uid = document.getElementById('currency').value;
	setMonthPrice(monthprices[currency_uid]);
	setImagesPrice(imageprices[currency_uid]);
	setCurrencyFormat(currencyFormats[currency_uid][0],currencyFormats[currency_uid][1],currencyFormats[currency_uid][2],currencyFormats[currency_uid][3]);
 	changeNumMonths(document.getElementById('num_months').value);
	changeNumImages(document.getElementById('num_images').value);
    document.getElementById('header_currency_iso_code').innerHTML = currency_iso_code;
	if (document.getElementById('month_price')) {
	    document.getElementById('month_price').innerHTML = formatCurrency(monthprices[currency_uid])+' '+currency_iso_code;
	}
	if (document.getElementById('images_price')) {
	    document.getElementById('images_price').innerHTML = formatCurrency(imageprices[currency_uid])+' '+currency_iso_code;
	}
}

/**
*
*
*/
function changeTotalPrice() {
    //alert("Mark 1");
    var num_months = document.getElementById('num_months').value;
    //alert("Mark 2");

    var num_images = document.getElementById('num_images').value;

    total = num_months*monthprice+num_images*imagesprice;
    temp = 1-(1/(1+vat));
    //  alert (temp.toFixed(2));
    subvat = total*temp;
    //alert("TEST");

    document.getElementById('total_incl_vat').innerHTML  = formatCurrency(total);
    document.getElementById('total_vat').innerHTML  = formatCurrency(subvat);
}

/**
*
*/
function setUserStorage(pid) {
	userstorage = pid;
}

/**
*
*/
function payment_login() {
 var username = document.getElementById('username').value;
 var password = document.getElementById('password').value;
 //alert("Logging in: "+username+"/"+password);
 var dojoUrl = 'index.php?id='+editor_uid+'&type=58&invitation='+invitationuid+'&cmd=login&logintype=login&pid='+userstorage+'&user='+username+'&pass='+password;
 dojo.io.bind({
    url: dojoUrl,
    load: function(type, data, evt) {
      document.getElementById('login_supercontainer').innerHTML = data;
    },
    mimetype: "text/plain",
    encoding: "utf-8"
    });
}

/**
*
*/
function payment_create_account() {
 var dojoUrl = 'index.php?id='+editor_uid+'&type=58&invitation='+invitationuid+'&cmd=createaccount';
 dojo.io.bind({
    url: dojoUrl,
    load: function(type, data, evt) {
      document.getElementById('login_supercontainer').innerHTML = data;
    },
    mimetype: "text/plain",
    encoding: "utf-8",
    formNode: document.getElementById("createuserform")
    });
}

