/**
 * @author Ellyx Christian
 */
function basePath(){
	var url = window.location.href;
	var urls = url.replace(/http:\/\//,'');
	urls = urls.split('/');
	var base = urls[0];
	if(urls[1]=='newlambada1'){
		base+='/'+urls[1];
	}
	return "http://"+base;
}
function moobbieGetWindowSize(){
    var viewportwidth;
    var viewportheight;
    
    // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
    
    if (typeof window.innerWidth != 'undefined') {
        viewportwidth = window.innerWidth, viewportheight = window.innerHeight
    }
    
    // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
    
    else 
        if (typeof document.documentElement != 'undefined' &&
        typeof document.documentElement.clientWidth !=
        'undefined' &&
        document.documentElement.clientWidth != 0) {
            viewportwidth = document.documentElement.clientWidth, viewportheight = document.documentElement.clientHeight
        }
        
        // older versions of IE
        
        else {
            viewportwidth = document.getElementsByTagName('body')[0].clientWidth, viewportheight = document.getElementsByTagName('body')[0].clientHeight
        }
    return new Array(viewportwidth, viewportheight);
}

function addOfficeAddress(party){
    $("body").append("<div id=\"officeAddressDialog\"/>");
    var dialog = $("#officeAddressDialog");
    $(dialog).dialog({
        autoOpen: false,
        modal: true,
        width: 700,
        title: 'Customer Management - Moobbie',
        bgiframe: true,
        buttons: {
            "Cancel": function(){
                $(this).dialog('close');
            },
            "Save": function(){
                $("#officeAddressDialog #formOffice").submit();
                //document.formOffice.submit();
                $("#loadOffAdd").show();
                $("#formOffAdd").hide();
            }
        },
        open: function(){
            $.ajax({
                url: basePath()+'/moobbie/customer-management/add-office-address/' + party + '.html',
                cache: false,
                dataType: 'html',
                success: function(data){
                    $(dialog).html('<div id="loadOffAdd" style="display:none;">Please wait...<br /><img src="images/pos/loading3.gif" alt="loading" /></div><div id="formOffAdd">' + data + '</div>');
                    $(dialog).dialog('option', 'position', 'center');
                    $("#formOffice #shopLuasTotal").keyup(function(){
                        $("#formOffice #totalSQ").val(parseFloat($(this).val()) + parseFloat($("#formOffice #shopTerass").val() ? $("#formOffice #shopTerass").val() : 0));
                    });
                    $("#formOffice #shopTerass").keyup(function(){
                        $("#formOffice #totalSQ").val(parseFloat($(this).val()) + parseFloat($("#formOffice #shopLuasTotal").val() ? $("#formOffice #shopLuasTotal").val() : 0));
                    });
                }
            });
        },
        close: function(){
            $(this).remove();
        }
    });
    $(dialog).dialog('open');
}

/**
 * functio to get geo assoc, get country from state, get state from country
 * @param {Object} geoId
 * @param {Object} selectId : select element id
 * @param Int param : index parameter, didocument harus ada hiden file dengan id 'nama function+Param' dan diisi dengan id div masing2 select
 * mulain dari state dipisahkan dengan tanda ~;
 */
function getGeoAssoc(geoId, selectId, param, form, lw){
    var arr = document.getElementById(form).getGeoAssocParam.value.split('~');
    if (param == 1) {
        doRequest('get', basePath()+'/moobbie/geo/create-select-country/' + geoId + '/' + selectId + '/' + form + '/true/' + lw + '.html', 'text', arr[param]);
    }
    else {
        doRequest('get', basePath()+'/moobbie/geo/get-state-from-country/' + geoId + '/' + selectId + '/' + form + '/true/' + lw + '.html', 'text', arr[param]);
    }
}

function afterSaveNewOfficeaddress(partyId){
    if (typeof showUpdateX == 'function') 
        showUpdateX(partyId);
    else {
    
        editCus1();
    }
    $("#officeAddressDialog").dialog('close');
    $("#officeAddressDialog").remove();
    var message = new MoobbieVanilaMessage('alert');
    message.setTitle('Customer Management - Moobbie');
    message.setContent('New Shop address has been saved');
    message.setOtherAction('OK', function(){
        return;
    }, true);
    message.show();
}

function viewOfficeAddress(party){
    $("body").append('<div id="officeDialog"/>');
    var dialog = $("#officeDialog");
    $(dialog).dialog({
        autoOpen: false,
        bgiframe: true,
        modal: true,
        width: $(window).width() - 20,
        title: 'Customer Management - Moobbie',
        buttons: {
            "Close": function(){
                $(this).dialog('close');
            }
        },
        open: function(){
            $(dialog).html('<div align="center"><img src="images/pos/loading3.gif" alt="loading..." /></div>');
            $.ajax({
                url: basePath()+'/moobbie/customer-management/list-office-address/' + party + '.html',
                cache: false,
                dataType: 'html',
                success: function(data){
                    $(dialog).html(data);
                    if ($(dialog).parent().height() > $(window).height() - 10) {
                        $(dialog).height($(window).height() - 110);
                        $(dialog).css('overflow', 'auto');
                    }
                    $(dialog).dialog('option', 'position', 'center');
                }
            });
        },
        close: function(){
            $(this).remove();
        }
    });
    $(dialog).dialog('open');
}

function saveOtherEmail(party){
    if (document.getElementById('temail').value == '') {
        alertMsg("Please Input email address!", '');
    }
    else {
        document.addemailform.submit();
        document.getElementById('loadingemail').innerHTML = '<img src="images/pos/loading3.gif" alt="loading" />';
        //moobbiePopuHide();
    }
}

function addOtherEmail(party){
    var xhtml = getXml();
    var popup = new MoobbiePopup('400');
    if (xhtml.readyState == 0 || xhtml.readyState == 4) {
        xhtml.open('GET', basePath()+'/moobbie/customer-management/add-other-email-address/' + party + '.html', true);
        xhtml.onreadystatechange = function(){
            if (xhtml.readyState == 4) {
                if (xhtml.status == 200) {
                    popup.setContent(xhtml.responseText);
                    popup.setTitle('Customer Management - Moobbie');
                    popup.setOtherAction('Save', "saveOtherEmail('" + party + "')");
                    popup.show();
                }
            }
        }
        xhtml.send(null);
    }
}

function viewOtherContact(party){
    document.getElementById('content_maxt').innerHTML = '<div align="center"><img src="images/loading.gif" alt="loading" align="absmiddle" /></div>';
    if (sendReq.readyState == 0 || sendReq.readyState == 4) {
        sendReq.open('GET', 'include/customer/edit_contact.php?view=' + party, true);
        sendReq.onreadystatechange = function(){
            if (sendReq.readyState == 4) {
                if (sendReq.status == 200) {
                    document.getElementById('content_maxt').innerHTML = sendReq.responseText;
                    //var st= document.getElementById('addemail');
                    //var w= st.offsetWidth ? st.offsetWidth : st.clientWidth;
                    //document.getElementById('addbtne').style.marginLeft=(w-150)+'px';
                    moobbiePopuHide();
                }
            }
        }
        sendReq.send(null);
    }
}

function viewListEmailAddress(party){
    if (document.getElementById('moobbiePopupDivContent')) {
        moobbiePopuHide();
    }
    var popup = new MoobbiePopup('600');
    if (xhtml.readyState == 0 || xhtml.readyState == 4) {
        xhtml.open('GET', basePath()+'/moobbie/customer-management/list-email-address/' + party + '.html', true);
        xhtml.onreadystatechange = function(){
            if (xhtml.readyState == 4) {
                if (xhtml.status == 200) {
                    popup.setContent(xhtml.responseText);
                    popup.setTitle('Customer Management > List Email Address - Moobbie');
                    //popup.setOtherAction('Save',"saveOtherEmail('"+party+"')");
                    popup.show();
                }
            }
        }
        xhtml.send(null);
    }
}

function viewPartyRelation(party, relType, scrn){
    //	carrierOtherContact
    document.getElementById('content_carrier').innerHTML = '<div align="center"><img src="images/pos/loading3.gif" alt="loading" align="absmiddle" /></div>';
    if (xhtml.readyState == 0 || xhtml.readyState == 4) {
        xhtml.open('GET', basePath()+'/moobbie/party-relationship/list-party-relation/' + party + '/' + relType + '/' + scrn + '.html', true);
        xhtml.onreadystatechange = function(){
            if (xhtml.readyState == 4) {
                if (xhtml.status == 200) {
                    document.getElementById('content_carrier').innerHTML = xhtml.responseText;
                }
            }
        }
        xhtml.send(null);
    }
}

function addNewRelation(party, relType, scrn){
    if (xhtml.readyState == 0 || xhtml.readyState == 4) {
        var wsize = moobbieGetWindowSize();
        if (wsize[0] >= 900) {
            var w = wsize[0] - 100;
        }
        else {
            var w = wsize[0] - 20;
        }
        var popup = new MoobbiePopup(w);
        xhtml.open('GET', basePath()+'/moobbie/party-relationship/new-party-relation/' + party + '/' + relType + '/' + scrn + '.html', true);
        xhtml.onreadystatechange = function(){
            if (xhtml.readyState == 4) {
                if (xhtml.status == 200) {
                    popup.setContent(xhtml.responseText);
                    popup.setTitle('Customer Management - Moobbie');
                    popup.show();
                }
            }
        }
        xhtml.send(null);
    }
}

function addEmailAddress(party){
    //addEmailAddress/
    if (xhtml.readyState == 0 || xhtml.readyState == 4) {
        var popup = new MoobbiePopup(600);
        xhtml.open('GET', basePath()+'/moobbie/customer-management/add-email-address/' + party + '.html', true);
        xhtml.onreadystatechange = function(){
            if (xhtml.readyState == 4) {
                if (xhtml.status == 200) {
                    popup.setContent(xhtml.responseText);
                    popup.setTitle('Customer Management > Add Email - Moobbie');
                    popup.show();
                }
            }
        }
        xhtml.send(null);
    }
}

function viewEditCarrier(party, btn, tx, sp){
    if (document.getElementById('content_carrier')) {
        document.getElementById('content_carrier').innerHTML = '<div align="center"><img alt="loading" src="images/pos/loading3.gif" /></div>';
    }
    else 
        document.getElementById('content_maxt').innerHTML = '<div align="center"><img alt="loading" src="images/pos/loading3.gif" /></div>';
    if (xhtml.readyState == 4 || xhtml.readyState == 0) {
        xhtml.open('GET', 'include/customer/edit_carrier.php?edit=' + party, true);
        xhtml.onreadystatechange = function(){
            if (xhtml.readyState == 4) {
                if (xhtml.status == 200) {
                    document.getElementById('content_maxt').innerHTML = xhtml.responseText;
                    var tab = new createTab(Array('Carrier Info', 'Other Contacts'), 'moobbietab');
                    tab.setAction(Array(' viewEditCarrier(' + party + ')', 'viewPartyRelation(\'' + party + '\',\'EMPLOYMENT\',\'carrier\')'));
                    tab.initTab();
                    //var st= document.getElementById('addemail');
                    //var w= st.offsetWidth ? st.offsetWidth : st.clientWidth;
                    //document.getElementById('addbtne').style.marginLeft=(w-150)+'px';
                    document.getElementById(tx).style.display = 'inline';
                    document.getElementById(tx).value = '';
                    document.getElementById(sp).style.display = 'none';
                    document.getElementById(btn).src = 'images/pos/check2.jpg';
                }
                else {
                    alert('Error In Making Request : ' + xhtml.statusText, '');
                }
            }
        }
        xhtml.send(null);
    }
}

function validateNewRelationContact(){
    var gender = '';
    var gen = document.formrel['gender'];
    for (var i = 0; gen[i]; i++) {
        if (gen[i].checked == true) {
            gender = gen[i].value;
        }
    }
    var message = new MoobbieVanilaMessage('alert');
    message.setTitle('Customer Management - Moobbie');
    if (gender == '') {
        message.setContent('Please select gender!');
        message.setOkAction();
        message.show();
        return false;
    }
    if (document.formrel['fname'].value == '') {
        message.setContent('Please Input First Name!');
        message.setOkAction();
        message.show();
        //document.formrel['fname'].focus();
        return false;
    }
    if (document.formrel['roleValue'].value == '') {
        message.setContent('Please choose position on company!');
        message.setOkAction();
        message.show();
        //document.formrel['roleValue'].focus();
        return false;
    }
    if (document.formrel['psw1'].value == '') {
        message.setContent('Please Input Password!');
        message.setOkAction();
        message.show();
        //document.formrel['psw1'].focus();
        return false;
    }
    if (document.formrel['psw2'].value == '') {
        message.setContent('Please Retype Password!');
        message.setOkAction();
        message.show();
        //document.formrel['psw2'].focus();
        return false;
    }
    if (document.formrel['psw2'].value != document.formrel['psw1'].value) {
        message.setContent('Password and Retype password must be same!');
        message.setOkAction();
        message.show();
        //document.formrel['psw1'].focus();
        return false;
    }
    message.hide();
    document.getElementById('formrel').submit();
}

function afterSaveNewCarrierOtherContact(party){
    viewPartyRelation(party, 'EMPLOYMENT', 'carrier');
    moobbiePopuHide();
}

function removeCarrierOtherContact(partyIdFr, partyIdTo){
    //removeRelation
    var popup = new MoobbieVanilaMessage('confirm');
    popup.setTitle('Customer Management - Moobbie');
    popup.setContent('Are you sure to delete this contact?');
    popup.setOtherAction('No', function(){
        return;
    }, true);
    popup.setOtherAction('Yes', function(){
        var xhtml = getXml();
        if (xhtml.readyState == 0 || xhtml.readyState == 4) {
            document.getElementById('content_carrier').innerHTML = '<div align="center"><img src="images/pos/loading3.gif" alt="loading" align="absmiddle" /></div>'
            xhtml.open('GET', basePath()+'/moobbie/party-relationship/remove-relation/' + partyIdFr + '/' + partyIdTo + '/EMPLOYMENT.html', true);
            xhtml.onreadystatechange = function(){
                if (xhtml.readyState == 4) {
                    if (xhtml.status == 200) {
                        doRequest('get', basePath()+'/moobbie/party-relationship/list-party-relation/' + partyIdFr + '/EMPLOYMENT/carrier.html', 'text', 'content_carrier');
                    }
                }
            }
            xhtml.send(null);
        }
    }, true);
    popup.show();
}

function editCarrierOtherContact(partyId, partyFr){
    var xhtml = getXml();
    if (xhtml.readyState == 0 || xhtml.readyState == 4) {
        var wsize = moobbieGetWindowSize();
        if (wsize[0] >= 900) {
            var w = wsize[0] - 100;
        }
        else {
            var w = wsize[0] - 20;
        }
        var popup = new MoobbiePopup(w);
        xhtml.open('GET', basePath()+'/moobbie/party-relationship/edit-carrier-other-contact/' + partyId + '/' + partyFr + '.html', true);
        xhtml.onreadystatechange = function(){
            if (xhtml.readyState == 4) {
                if (xhtml.status == 200) {
                    popup.setContent(xhtml.responseText);
                    popup.setTitle('Customer Management - Moobbie');
                    popup.show();
                }
            }
        }
        xhtml.send(null);
    }
}

function afterEditCarrierOtherContact(partyId, partyForm, screen1){
    viewPartyRelation(partyForm, 'EMPLOYMENT', screen1);
    editCarrierOtherContact(partyId, partyForm);
}

function getOfflineSO(){
    document.getElementById('history_content').innerHTML = '<table width="100%" border="0" cellspacing="0" cellpadding="0">' +
    '<tr>' +
    '<td height="500" align="center" valign="middle"><img src="images/loading.gif" width="30" height="30" alt="loading" style="filter:alpha(opacity=100); opacity:1;" /></td>' +
    '</tr>' +
    ' </table>';
    doRequest('get', 'include/pos/offline_so.php?pi=' + document.getElementById('cus_id_xxx').innerHTML, 'text', 'history_content');
}

function newOffSo(){
    showDialog4('Back to previous screen');
    document.getElementById('content_maxt').innerHTML = '<table width="100%" border="0" cellspacing="0" cellpadding="0">' +
    '<tr>' +
    '<td height="500" align="center" valign="middle"><img src="images/loading.gif" width="30" height="30" alt="loading" style="filter:alpha(opacity=100); opacity:1;" /></td>' +
    '</tr>' +
    ' </table>';
    doRequest('get', 'include/pos/new_offline_so.php?pi=' + document.getElementById('cus_id_xxx').innerHTML, 'text', 'content_maxt');
}

function getHistoryTab(){
    if (typeof getOrderHis == 'function') {
		if(!document.getElementById('tab_history')){
			getOrderHis();
			return;
		}
        getHistory();
    }
    else {
        getHistoryTab2('content_max');
    }
}

function showSoAfterUp(){
    document.getElementById('history_content').innerHTML = '<table width="100%" border="0" cellspacing="0" cellpadding="0">' +
    '<tr>' +
    '<td height="500" align="center" valign="middle"><img src="images/loading.gif" width="30" height="30" alt="loading" style="filter:alpha(opacity=100); opacity:1;" /></td>' +
    '</tr>' +
    ' </table>';
    document.getElementById('load_so').innerHTML = 'Data successfully Uploaded';
    if (xhtml.readyState == 4 || xhtml.readyState == 0) {
        xhtml.open('GET', 'include/pos/offline_so.php?pi=' + document.getElementById('cus_id_xxx').innerHTML, true);
        xhtml.onreadystatechange = function(){
            if (xhtml.readyState == 4) {
                if (xhtml.status == 200) {
                    document.getElementById('maximizex').style.display = 'none';
                    document.getElementById('history_content').innerHTML = xhtml.responseText;
                }
                else {
                    alertMsg('Error : ' + xhtml.statusText, '');
                }
            }
        }
        xhtml.send(null);
    }
}

function shopAddPicture(id){
    $("body").append('<div id="shopPictureDialog"><div align="center"><img src="images/pos/loading3.gif" alt="loading" /></div></div>');
    var dialog = $("#shopPictureDialog");
    $(dialog).dialog({
        autoOpen: false,
        bgiframe: true,
        modal: true,
        width: 900,
        title: 'Customer Management - Moobbie',
        buttons: {
            "Close": function(){
                $(this).dialog('close');
            }
        },
        open: function(){
            loadShopPicture(id);
        },
        close: function(){
            $(this).remove();
        }
    });
    $(dialog).dialog('open');
}

function loadShopPicture(id){
    $.ajax({
        url: basePath()+'/moobbie/customer-management/view-add-shop-picture/' + id + '.html',
        cache: false,
        dataType: 'html',
        success: function(data){
            $("#shopPictureDialog").html(data);
            if ($("#shopPictureDialog").parent().height() > $(window).height() - 10) {
                $("#shopPictureDialog").height($(window).height() - 110);
                $("#shopPictureDialog").css('overflow', 'auto');
            }
            $("#shopPictureDialog").dialog('option', 'position', 'center');
            $("a.fancy").fancybox({
                zoomSpeedIn: 300,
                zoomSpeedOut: 300,
                overlayShow: true
            });
        }
    });
}

function addViewShopVideo(id){
    $("body").append('<div id="shopVideoDialog"><div align="center"><img src="images/pos/loading3.gif" alt="loading" /></div></div>');
    var dialog = $("#shopVideoDialog");
    $(dialog).dialog({
        autoOpen: false,
        bgiframe: true,
        modal: true,
        width: 700,
        title: 'Customer Management - Moobbie',
        open: function(){
            loadShoVideo(id);
        },
        close: function(){
            $(this).remove();
        },
        buttons: {
            "Close": function(){
                $(this).dialog('close');
            }
        }
    });
    $(dialog).dialog('open');
}

function loadShoVideo(id){
    $.ajax({
        url: basePath()+'/moobbie/customer-management/view-add-shop-video/' + id + '.html',
        cache: false,
        dataType: 'html',
        success: function(data){
            $("#shopVideoDialog").html(data);
            if ($("#shopVideoDialog").parent().height() > $(window).height() - 10) {
                $("#shopVideoDialog").height($(window).height() - 110);
                $("#shopVideoDialog").css('overflow', 'auto');
            }
            $("#shopVideoDialog").dialog('option', 'position', 'center');
            $("#tablevideo tr:nth-child(even)").css('background', '#ccffcc');
            $("#tablevideo tr:nth-child(odd)").css('background', '#ffcc99');
        }
    });
}

function deleteShopFile(id, id2, type){
    $("body").append("<div id='msgShopFile'><strong>Are you sure to delete this file?</strong></div>");
    $("#msgShopFile").dialog({
        bgiframe: true,
        modal: true,
        autoOpen: false,
        title: 'Customer Management - Moobbie',
        buttons: {
            "No": function(){
                $(this).dialog('close');
            },
            "Yes": function(){
                $(this).html('<div align="center"><img src="images/pos/loading3.gif" alt="loading" /></div>');
                $.ajax({
                    url: basePath()+'/moobbie/party-shop-file/delete/' + id + '.html',
                    cache: false,
                    dataType: 'html',
                    success: function(){
                        $("#msgShopFile").dialog('close');
                        if (!type) {
                            loadShopPicture(id2);
                        }
                        else {
                            loadShoVideo(id2);
                        }
                    }
                });
            }
        },
        close: function(){
            $("#msgShopFile").remove();
        }
    });
    $("#msgShopFile").dialog('open');
}

function editImportListCountry(party){
    $("body").append("<div id=\"editImportDiaog\"/>");
    $("#editImportDiaog").dialog({
        modal: true,
        autoOpen: false,
        bgiframe: true,
        title: 'Customer Management - Moobbie',
        width: 600,
        buttons: {
            "Close": function(){
                $(this).dialog('close');
            }
        },
        close: function(){
            $(this).remove();
        },
        open: function(){
            loadEditListImportCountryContent(party);
        }
    });
    $("#editImportDiaog").dialog('open');
}

function loadEditListImportCountryContent(party){
    if (party == '') 
        party = 'new';
    $("#editImportDiaog").html('<div align="center"><img src="images/pos/loading3.gif" alt="loading" /></div>');
    var link = basePath()+'/moobbie/customer-management/editImportListCountry/' + party + '.html';
    if (document.getElementById("importlist")) {
        link = basePath()+'/moobbie/customer-management/editImportListCountry/' + party + '/Y.html';
    }
    $.ajax({
        url: link,
        cache: false,
        success: function(data){
            $("#editImportDiaog").html(data);
            /*if (!document.getElementById("importlist")) {
             if (typeof showUpdateX == 'function')
             showUpdateX(party);
             else
             editCus1();
             }else{*/
            $("#importListText").html($("#listCountryImport").val().split('~').join(', '));
            //}
            $("#editImportDiaog").dialog('option', 'position', 'center');
        }
    });
}

function addListImport(party){
    $("#listCountryImport").val($("#listCountryImport").val() + $("#listGeo").val() + '~');
    saveListImport(party);
}

function saveListImport(party){
    var data = {
        partyId: party,
        listCountry: $("#listCountryImport").val(),
        action: 'save'
    };
    $("#editImportDiaog").html('<div align="center"><img src="images/pos/loading3.gif" alt="loading" /></div>');
    var link = basePath()+'/moobbie/party-group/addCountryImport.html';
    if (document.getElementById("importlist")) {
        link = basePath()+'/moobbie/party-group/addCountryImport/Y.html';
    }
    $.post(link, data, function(respon){
        loadEditListImportCountryContent(party);
    });
}

var oldShip1, oldShip2, oldShipCity, oldShipZip, oldShipState, oldShipCounty,oldToName;
var olds1,olds2,olds3,oldf1,oldf2,oldf3;
function copyBillingToShipping(){
    var copy = $("input[name='copy']:checked").val();
    if (copy) {
        oldShip1 = $("#sadd1").val();
        oldShip2 = $("#sadd2").val();
        oldShipCity = $("#scity").val();
        oldShipZip = $("#szip").val();
        oldShipState = $("#sstate").val();
        oldShipCounty = $("#scountry").val();
	oldToName = $("#sName").val();
        olds1 = $("#spd1").val();
        olds2 = $("#spd2").val();
        olds3 = $("#spd3").val();
        oldf1 = $("#sf1").val();
        oldf2 = $("#sf2").val();
        oldf3 = $("#sf3").val();
        $("#sadd1").val($("#badd1").val());
        $("#sadd2").val($("#badd2").val());
        $("#scity").val($("#bcity").val());
        $("#szip").val($("#bzip").val());
        $("#sstate").val($("#bstate").val());
        $("#scountry").val($("#bcountry").val());
	$("#sName").val($("#bName").val());
        $("#spd1").val($("#bp1").val());
        $("#spd2").val($("#bp2").val());
        $("#spd3").val($("#bp3").val());
        $("#sf1").val($("#bf1").val());
        $("#sf2").val($("#bf2").val());
        $("#sf3").val($("#bf3").val());
    }
    else {
        $("#sadd1").val(oldShip1);
        $("#sadd2").val(oldShip2);
        $("#scity").val(oldShipCity);
        $("#szip").val(oldShipZip);
        $("#sstate").val(oldShipState);
        $("#scountry").val(oldShipCounty);
	$("#sName").val(oldToName);
        $("#spd1").val(olds1);
        $("#spd2").val(olds2);
        $("#spd3").val(olds3);
        $("#sf1").val(oldf1);
        $("#sf2").val(oldf2);
        $("#sf3").val(oldf3);
    }
}

function checkLowForm(){
    var ch = $("input[name='lowFull']:checked").val();
    if (ch == 1) {
        if ($("#company").val() == '') {
            $("#company").val($("#underName").val());
        }
        $("#underName").attr('readonly', 'readonly');
        $("#company").removeAttr('readonly');
    }
    else {
        if ($("#underName").val() == '') {
            $("#underName").val($("#company").val());
        }
        $("#underName").removeAttr('readonly');
        $("#company").attr('readonly', 'readonly');
    }
}

function loadContentAdvanceInfo(party){
    $("#advanceInfo").html('<div align="center"><img src="images/pos/loading3.gif" alt="loading..." /></div>');
    $.ajax({
        url: basePath()+'/moobbie/customer-management/party-advanced-info/' + party + '.html',
        cache: false,
        success: function(data){
            $("#contentx").html(data);
        }
    });
}

function loadContentAdvanceInfo1(party){
    $("#advanceInfo").html('<div align="center"><img src="images/pos/loading3.gif" alt="loading..." /></div>');
    $.ajax({
        url: basePath()+'/moobbie/customer-management/party-advanced-info/' + party + '.html',
        cache: false,
        success: function(data){
            $("#advanceInfo").html(data);
        }
    });
}

function partyAdvanceInfo(party){
	document.getElementById('savex').style.display='none';
    $("body").append("<div id='advanceInfo'/>");
    var dialog = $("#advanceInfo");
    $(dialog).dialog({
        modal: true,
        buttons: {
            "Close": function(){
                $(this).dialog('close');
            },
            "Save": function(){
                $("#formAdvance").submit();
            }
        },
        title: 'Customer Management &raquo; Advanced Info - Moobbie',
        width: $(window).width() - 10,
        height: $(window).height() - 10,
        close: function(){
            $("#advanceInfo").remove();
			closeExpandInfo();
        },
        open: function(){
            loadContentAdvanceInfo1(party);
        }
    });
    $(dialog).dialog('open');
}
function closeExpandInfo(){
	if(window.location.href.search(/administration/)==-1){
		window.location.href=basePath()+'/member-area.php?msg=1';
	}
}
function saveAdvanceInfo(party){
    var param = '&summerFrom=' + $("#summerFrom").val() + '&summerTo=' + $("#summerTo").val();
    param += '&winterFrom=' + $("#winterFrom").val() + '&winterTo=' + $("#winterTo").val();
    param += '&periodAll=' + $("#periodAll:checked").val() + '&proNormal=' + $('#proNormal').val();
    param += '&proCons=' + $("#proCons").val();
}

function loadRelation(party){
    $('#relationsDialog').html('<div align="center"><img src="images/pos/loading3.gif" alt="loading..." /></div>');
    $.ajax({
        url: basePath()+'/moobbie/customer-management/add-relations/' + party + '.html',
        cache: false,
        success: function(data){
            $('#relationsDialog').html(data);
            loadParty('CUSTOMER', 1, 'selectPartyRelation');
        }
    });
}

function loadParty(type, page, action){
    $('#listCustomerHere').html('<div align="center"><img src="images/pos/loading3.gif" alt="loading..." /></div>');
    $.ajax({
        url: basePath()+'/moobbie/customer-management/list-party/' + type + '/' + page + '/' + action + '.html',
        cache: false,
        success: function(hsl){
            $('#listCustomerHere').html(hsl);
        }
    });
}

function selectPartyRelation(partyIdTo){
    var partyIdFrom = $("#partyIdFrom").val();
    $("#relationsDialog").html('<div align="center"><img src="images/pos/loading3.gif" alt="loading..." /></div>');
    
    $.get(basePath()+'/moobbie/customer-management/add-relation/' + partyIdFrom + '/' + partyIdTo + '/FRIEND.html', {}, function(data){
        contactHistory(partyIdFrom);
        $("#relationsDialog").dialog('close');
    });
}

function searchCustomerList(type, action){
    var form = document.forms['searchForm'];
    if (form.c_class.checked == false && form.c_country.checked == false && form.c_company.checked == false && form.c_name.checked == false && form.c_cus_id.checked == false && form.c_city.checked == false && form.c_email.checked == false) {
        var message = new MoobbieVanilaMessage('confirm');
        message.setTitle('Customer Management - Moobbie');
        message.setContent('Please choose search by option!');
        message.addButton('OK', function(){
        }, true);
        message.show();
    }
    else {
        var clas = 'N';
        var country = 'N';
        var comp = 'N';
        var name = 'N';
        var cus_id = 'N';
        var t_clas = '';
        var t_country = '';
        var t_comp = '';
        var t_name = '';
        var t_cus_id = '';
        var city = 'N';
        var t_city = '';
        var email = 'N';
        var t_email = '';
        if (form.c_class.checked == true) {
            //alert('test');
            clas = 'Y';
            t_clas = form.s_class.value;
        }
        if (form.c_country.checked == true) {
            //alert('test');
            country = 'Y';
            t_country = form.t_country.value;
            //alert('test');
        }
        if (form.c_company.checked == true) {
            //alert('test');
            comp = 'Y';
            t_comp = form.t_company.value;
        }
        if (form.c_name.checked == true) {
            //alert('test');
            name = 'Y';
            t_name = form.t_name.value;
        }
        if (form.c_cus_id.checked == true) {
            //alert('test');
            cus_id = 'Y';
            t_cus_id = form.t_cus_id.value;
        }
        if (form.c_city.checked == true) {
            city = 'Y';
            t_city = form.t_city.value;
        }
        if (form.c_email.checked == true) {
            email = 'Y';
            t_email = form.t_email.value;
        }
        var param = 'action=search';
        param += '&class=' + clas + '&t_class=' + t_clas + '&country=' + country + '&t_country=' + t_country + '&company=' + comp + '&t_company=' + t_comp + '&name=' + name + '&t_name=' + t_name + '&cus_id=' + cus_id + '&t_cus_id=' + t_cus_id + '&city=' + city + '&t_city=' + t_city + '&email=' + email + '&t_email=' + t_email;
        $('#listCustomerHere').html('<div align="center"><img src="images/pos/loading3.gif" alt="loading" /><br />Please Wait</div>');
        $.post(basePath()+'/moobbie/customer-management/list-party/' + type + '/1/' + action + '.html', param, function(data){
            $('#listCustomerHere').html(data);
            //new TableColor('table_inactive_customer','#ccffcc','','','');
        });
    }
}

function addRelations(party){
    $("body").append("<div id='relationsDialog'/>");
    var dialog = $("#relationsDialog");
    $(dialog).dialog({
        modal: true,
        bgiframe: true,
        title: 'Customer Management &raquo; Add Relation - Moobbie',
        width: $(window).width() - 40,
        height: $(window).height() - 40,
        autoOpen: false,
        buttons: {
            "Close": function(){
                $(this).dialog('close');
            }
        },
        open: function(){
            loadRelation(party);
        },
        close: function(){
            $("#relationsDialog").remove();
        }
    });
    $(dialog).dialog('open');
}

function addCompetitors(party){
    $("body").append("<div id='competitorDialog'/>");
    var dialog = $("#competitorDialog");
    $(dialog).dialog({
        modal: true,
        bgiframe: true,
        title: 'Customer Management &raquo; Add Competitor - Moobbie',
        width: $(window).width() - 40,
        height: $(window).height() - 40,
        autoOpen: false,
        buttons: {
            "Close": function(){
                $(this).dialog('close');
            }
        },
        open: function(){
            loadCompetitor(party);
        },
        close: function(){
            $("#competitorDialog").remove();
        }
    });
    $(dialog).dialog('open');
}

function loadCompetitor(party){
    $('#competitorDialog').html('<div align="center"><img src="images/pos/loading3.gif" alt="loading..." /></div>');
    $.ajax({
        url: basePath()+'/moobbie/customer-management/add-competitor/' + party + '.html',
        cache: false,
        success: function(data){
            $('#competitorDialog').html(data);
            loadParty('COMPETITOR', 1, 'selectCompetitor');
        }
    });
}

function selectCompetitor(partyIdTo){
    var partyIdFrom = $("#partyIdFrom").val();
    $("#competitorDialog").html('<div align="center"><img src="images/pos/loading3.gif" alt="loading..." /></div>');
    
    $.get(basePath()+'/moobbie/customer-management/add-relation/' + partyIdFrom + '/' + partyIdTo + '/COMPETITOR.html', {}, function(data){
        contactHistory(partyIdFrom);
        $("#competitorDialog").dialog('close');
    });
}

function newCompetitor(party){
    $("body").append('<div id="newCompetitorDialog"><div align="center"><img src="images/pos/loading3.gif" alt="loading..." /></div></div>');
    var dialog = $("#newCompetitorDialog");
    $(dialog).dialog({
        modal: true,
        bgiframe: true,
        autoOpen: false,
        title: 'Customer Management &raquo; New Competitor - Moobbie',
        width: $(window).width() - 70,
        height: $(window).height() - 70,
        buttons: {
            "Cancel": function(){
                $(this).dialog('close');
            },
            "Save": function(){
                if ($("#companyName").val().trim() == '') {
                    alert('Please input Company Name!', '');
                    $("#companyName").focus();
                    return false;
                }
                $("#competitorForm").submit();
            }
        },
        open: function(){
            $.ajax({
                url: basePath()+'/moobbie/customer-management/new-competitor/'+party+'.html',
                cache: false,
                success: function(data){
                    $("#newCompetitorDialog").html(data);
                }
            });
        },
        close: function(){
            $("#newCompetitorDialog").remove();
        }
    });
    $(dialog).dialog('open');
}

function afterSaveCompetitor(){
    loadParty('COMPETITOR', 1, 'selectCompetitor');
    $("#newCompetitorDialog").dialog('close');
}

function removeRelation(fr, to, type){
    $("body").append("<div id='confirmDel'><strong>Are you sure to delete this relations?</strong></div>");
    $("#confirmDel").dialog({
        autoOpen: false,
        modal: true,
        title: 'Customer Management - Moobbie',
        bgiframe: true,
        buttons: {
            "No": function(){
                $(this).dialog('close');
            },
            "Yes": function(){
                $("#confirmDel").html('<div align="center"><img src="images/pos/loading3.gif" alt="loading..." /></div>');
                $.get(basePath()+'/moobbie/party-relationship/remove-relation/' + fr + '/' + to + '/' + type + '.html', {}, function(){
                    contactHistory(fr);
                    $("#confirmDel").dialog('close');
                });
            }
        },
        close: function(){
            $("#confirmDel").remove();
        }
    });
    $("#confirmDel").dialog('open');
}

function contactHistory(party){
    document.getElementById('tab').style.background = 'url(images/tab/tab_05.jpg) left bottom no-repeat';
    $("#contentx").html('<img src="images/loading.gif" alt="Loading" width="30" height="30" align="absmiddle" />Loading....');
    $.ajax({
        url: basePath()+'/moobbie/customer-management/contact-history/' + party + '.html',
        cache: false,
        success: function(data){
            $("#contentx").html(data);
        }
    })
}

function loadUserLoginHistory(party, page){
    $(".contentHistory").html('<div align="center"><img src="images/pos/loading3.gif" alt="loading..." /></div>');
    $.ajax({
        url: basePath()+'/moobbie/customer-management/user-login-history/' + party + '/' + page + '.html',
        cache: false,
        success: function(data){
            $(".contentHistory").html(data);
        }
    });
}

function newActivities(party){
    $("body").append('<div id="activitiesDialog"><div align="center"><img src="images/pos/loading3.gif" alt="loading..." /></div></div>');
    $("#activitiesDialog").dialog({
        modal: true,
        bgiframe: true,
        width: 600,
        autoOpen: false,
        title: 'Customer Management &raquo; New Contact History - Moobbie',
        buttons: {
            "Close": function(){
                $(this).dialog('close');
            },
            "Save": function(){
                if ($("#subject").val().split(' ').join('') == '') {
                    alert('Please input subject');
                    $("#subject").focus();
                    return false;
                }
				$("#activitiesDialog").dialog('option', 'buttons', {});
                $("#formContact").submit();
            }
        },
        open: function(){
            $.ajax({
                url: basePath()+'/moobbie/customer-management/new-activities/' + party + '.html',
                cache: false,
                success: function(data){
                    $("#activitiesDialog").html(data);
                    $("#activitiesDialog").dialog('option', 'position', 'center');
                }
            });
        },
        close: function(){
            $("#activitiesDialog").remove();
        }
    });
    $("#activitiesDialog").dialog('open');
}

function loadContacHistory(party, page){
    $(".contentContactHistory").html('<div align="center"><img src="images/pos/loading3.gif" alt="loading..." /></div>');
    $.ajax({
        url: basePath()+'/moobbie/customer-management/activities/' + party + '/' + page + '.html',
        cache: false,
        success: function(data){
            $(".contentContactHistory").html(data);
        }
    });
}

function afterSaveActivities(party){
    $("#activitiesDialog").dialog('close');
    loadContacHistory(party, 1);
}
function loadOtherCOntact(party){
	$.ajax({
                url: 'include/customer/get_employe.php?pi=' + party,
                cache: false,
                success: function(data){
                    $("#otherCOntactDialog").html(data);
                }
            });
}
function viewOtherContactMain(party){
    $("body").append('<div id="otherCOntactDialog"><div align="center"><img src="images/pos/loading3.gif" alt="loading..." /></div></div>')
    $("#otherCOntactDialog").dialog({
        modal: true,
        bgiframe: true,
        autoOpen: false,
        width: $(window).width() - 40,
        height: $(window).height() - 40,
        title: 'Customer Management &raquo; View Other Contact - Moobbe',
        open: function(){
            loadOtherCOntact(party);
        },
        close: function(){
            $("#otherCOntactDialog").remove();
        },
        buttons: {
            "Close": function(){
                $(this).dialog('close');
            }
        }
    });
    $("#otherCOntactDialog").dialog('open');
}

function addOtherContactMain(){
    $("body").append('<div id="addCOntactDialog"><div align="center"><img src="images/pos/loading3.gif" alt="loading..." /></div></div>');
    $("#addCOntactDialog").dialog({
        modal: true,
        bgiframe: true,
        autoOpen: false,
        title: 'Customer Management &raquo; Add Other Contact - Moobbie',
        width: $(window).width() - 40,
        height: $(window).height() - 40,
        buttons: {},
        open: function(){
            $.post('include/customer/add_contact.php', {
                company: $("#hide_comp").html()
            }, function(data){
                $("#addCOntactDialog").html(data);
            });
        },
        close: function(){
            $("#addCOntactDialog").remove();
        },
		buttons:{
			"Close":function(){
				$(this).dialog('close');
			}
		}
    });
    $("#addCOntactDialog").dialog('open');
    
}

function createNewCustomer(websiteId, fromWebsite){
	$("body").append('<div id="createNewCustomerDialog"><div align="center"><img src="images/pos/loading3.gif" alt="loading..." /></div></div>');
	$("#createNewCustomerDialog").dialog({
		modal:true,
		autoOpen:false,
		bgiframe:true,
		title : 'Customer Management &raquo; Create New Customer - Moobbie',
		width : 400,
		buttons : {
			"Cancel":function(){
				$(this).dialog('close');
			},
			"Save & Continue": function(){
				formSubmit();
			}
		},
		open : function(){
			$.ajax({
				url : basePath() + '/moobbie/customer-management/new-customer.html',
				cache : false,
				success : function(response){
					$("#createNewCustomerDialog").html(response);
					$("#createNewCustomerDialog").dialog('option', 'position', 'center');
					if (websiteId) {
						$("#createNewCustomerDialog #websiteId").val(websiteId);
					}
					if(fromWebsite){
						$("#createNewCustomerDialog #fromWebsite").val(fromWebsite);
					}
				}
			});
		},
		close : function(){
			$("#createNewCustomerDialog").remove();
		}
	});
	$("#createNewCustomerDialog").dialog('open');
}

function saveNewCustomerSimple(partyId, userLoginId, password){
	$("#createNewCustomerDialog").dialog('close');
	if (typeof showUpdate == 'function') {
		showUpdate(userLoginId, partyId);
	}
	else {
		selectCusNew(partyId);
	}
	/*$("body").append('<div id="saveNewCustomerDialog"><strong>Please remember to change your user login information!<br />Your temporary user login information are : <br /><span style="color:#FFFFFF;">User Name : '+userLoginId+'<br />Password : '+password+'</span></strong></div>');
	$("#saveNewCustomerDialog").dialog({
		modal : true,
		autoOpen : false,
		bgiframe : true,
		title : 'Customer Management - Moobbie',
		width : 500,
		buttons : {
			"OK" : function(){
				$(this).dialog('close');
			}
		}
		,close : function(){
			$("#saveNewCustomerDialog").remove();
		}
	});
	$("#saveNewCustomerDialog").dialog('open');*/
}
function formSubmit(){
		if($("#createNewCustomerDialog #company").val() == '' && $("#createNewCustomerDialog #underName").val() == ''){
			alert('Please input your company name');
			return false;
		}
		if($("#createNewCustomerDialog #email").val() == ''){
			alert("Please input email address");
			return false;
		}
		if($("#createNewCustomerDialog #pass1").val() == ''){
			alert("Please input password");
			return false;
		}
		if($("#createNewCustomerDialog #pass1").val() != $("#createNewCustomerDialog #pass2").val()){
			alert("Password and retype password must be the same");
			return false;
		}
		$("#createNewCustomerDialog #formNewCustomer").submit();
	}

function validateCustomerRequiredField(){
	var class_pty=$("input[name='class_pty']:checked").val();
	var notValidPhone=/\D/;
	var pos='';
    
    if (document.getElementById('c_emp').checked) {
        pos += document.getElementById('c_emp').value + '-';
    }
    if (document.getElementById('c_man').checked) {
        pos += document.getElementById('c_man').value + '-';
    }
    if (document.getElementById('c_buyer').checked) {
        pos += document.getElementById('c_buyer').value + '-';
    }
    if (document.getElementById('c_owner').checked) {
        pos += document.getElementById('c_owner').value + '-';
    }
    if (document.getElementById('c_sale').checked) {
        pos += document.getElementById('c_sale').value + '-';
    }
	var filter=/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
	if($("input[name='gender']:checked").val() == undefined || $("input[name='gender']:checked").val() == ''){
		alert(__("Please select gender"));
		document.getElementById('radiobutton').focus();
	}else if(document.getElementById('name').value==''){
		alert(__('Please input First name'),'');
		document.getElementById('name').focus();
	}else if(document.getElementById('company').value=='' && $("#underName").val()==''){
		alert(__('Please input company name'),'');
		document.getElementById('company').focus();
	}else if(pos==''){
		alert(__("Please select position in company"),'');
		document.getElementById('c_owner').focus();
	}else if(class_pty== undefined){
		alert(__("Please select classification"),'');
		document.getElementById('r2').focus();
	}else if(document.getElementById('email').value==''){
		alert(__('Please input email address'),'');
		document.getElementById('email').focus();
	}else if(!filter.test(document.getElementById('email').value)){
		alert(__('Please input the correct email'),'');
		document.getElementById('email').foucs();
	}else if(document.getElementById('password').value==''){
		alert(__('Please input password'),'');
		document.getElementById('password').focus();
	}else if(document.getElementById('password1').value==''){
		alert(__('Please input confirm password'),'');
		document.getElementById('password1').focus();
	}else if(document.getElementById('password').value!=document.getElementById('password1').value){
		alert(__('Password and Confirm password must be the same'),'');
		document.getElementById('password').focus();
	}else if(document.getElementById('p1').value=='' || document.getElementById('p2').value=='' || document.getElementById('p3').value=='' ){
		alert(__('Please input phone number'),'');
		document.getElementById('p1').focus();
	}else if(notValidPhone.test(document.getElementById('p1').value) || notValidPhone.test(document.getElementById('p2').value) || notValidPhone.test(document.getElementById('p3').value) ){
		alert(__('Please input valid phone number'),'');
		document.getElementById('p1').focus();
	}else if(document.getElementById('badd1').value==''){
		alert(__('Please input Billing address 1'),'');
		document.getElementById('badd1').focus();
	}else if(document.getElementById('bcity').value==''){
		alert(__('Please input Billing address city'),'');
		document.getElementById('bcity').focus();
	}else if(document.getElementById('bzip').value==''){
		alert(__('Please input billing address zip code'),'');
		document.getElementById('bzip').focus();
	}else if(document.getElementById('bcountry').value==''){
		alert(__('Please input billing address country'),'');
		document.getElementById('bcountry').focus();
	}else if(document.getElementById('sadd1').value==''){
		alert(__('Please input shipping address 1'),'');
		document.getElementById('sadd1').focus();
	}else if(document.getElementById('scity').value==''){
		alert(__('Please input shipping address city'),'');
		document.getElementById('scity').focus();
	}else if(document.getElementById('szip').value==''){
		alert(__('Please input shipping address zip code'),'');
		document.getElementById('szip').focus();
	}else if(document.getElementById('scountry').value==''){
		alert(__('Please input shipping address country'),'');
		document.getElementById('scountry').focus();
	}else if (document.getElementById('c_owner').checked == false && document.getElementById('c_man').checked == false && document.getElementById('c_emp').checked == false && document.getElementById('c_buyer').checked == false && document.getElementById('c_sale').checked == false) {
		alert(__('Please choose position in company'),'');
		document.getElementById('c_owner').focus();
	}else{
	return true;
	}
	return false;
}
