﻿/* ---------------------------------------------------------------------- *\
BİRDENBİRE # Ali BİNGÖL 01/11/2009#
\* ---------------------------------------------------------------------- */

//Ver 1.0
//02/03 --emptycopmbo--> cmb_empty
//02/03 cmb_add eklendi
//01/07 UC_AIR Eklendi
//15/08 cNumeric eklendi
//04/11/10  ToDate,DateToStr MY.eklendi, ve DAT içindeki COnverttOsTR Silindi
//12/11/10 AirObjesi değişti
//07/01/11 DAT objesine focus eklendi
//07/01/11 StripTags eklendi
//25/5/11   PrintTime eklendi
//30/5/11   PrintTime2 eklendi
//03/6/11   ucAir değişti 
//07/07/11  IsValidEMail eklendi
//04/08/11 replaceAll eklendi
//17/08/11  CheckNumeric eklendi, TEXT obj değişti
//17/08/11  CKEditor değişti
//----------------------------
//12/10/11  
//Ver 2.0
//21/10/2011    cNumeric degisti,StrSub eklendi
//15/12/11      StrTruncateLast  eklendi
//20/01/12      formatMoney buraya taşındı common.js'den

Number.prototype.formatMoney = function(c, d, t) {
    var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}


var MY = new function() {
    /* ---------------------------------------------------------------------- *\
    Common js
    \* ---------------------------------------------------------------------- */
    this.DayDiff = function(dt1, dt2) {
        return Math.floor((dt2 - dt1) / 86400000);
    }
    //en sondaki tag'den sonraki her şeyi uçurur. Meslea d:\xyz\abc\val 'den d:\xyz\abc geri gelir
    this.StrTruncateLast = function(val, tag) {
        var ind = val.lastIndexOf(tag)
        if (ind == -1) return ''
        return val.substring(0, ind)
    }
    //tag1 ve 2 arasını getirir
    this.StrSub = function(val, tag1, tag2) {
        var ind1 = val.match(tag1)
        if (!ind1) return ''
        var sRemain = val.substring(ind1.lastIndex)
        var ind2 = sRemain.match(tag2)
        if (!ind2) return ''
        return sRemain.substring(0, ind2.index)
    }
    //StripTags     
    this.stripTags = function(val) {
        return val.replace(/<\/?[^>]+>/gi, '');
    }
    //Validate eMail
    this.IsValidEMail = function(email) {
        var pattrn = /^[\w-]+(\.[\w-]+)*@([a-z0-9-]+(\.[a-z0-9-]+)*?\.[a-z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?$/
        return email.match(pattrn)
    }
    //today
    this.Today = function() {
        return new Date()
    }
    //print Time
    this.PrintTime = function(duration) {
        var hr = 0, mnt
        if (duration > 59) hr = parseInt(duration / 60)
        mnt = duration - (hr * 60)
        //
        if (hr < 10) hr = '0' + hr
        if (mnt < 10) mnt = '0' + mnt
        return hr + ':' + mnt
    }
    this.PrintTime2 = function(duration) {
        var hr = 0, mnt
        if (duration > 59) hr = parseInt(duration / 60)
        mnt = duration - (hr * 60)
        //
        return hr + ' saat ' + mnt + ' dakika'
    }
    //IsDate
    this.IsDate = function(val) {
        if (val == 'undefined') return false;
        if (val == null) return false;
        var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
        var matchArray = val.match(datePat);
        if (matchArray == null) return false;

        day = matchArray[1];
        month = matchArray[3];
        year = matchArray[5];

        if (month < 1 || month > 12) return false; // check month range	
        if (day < 1 || day > 31) return false;
        if ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31) return false;

        if (month == 2) { // check for february 29th
            var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
            if (day > 29 || (day == 29 && !isleap)) return false;
        }
        return true;
    }
    //IsTime
    this.IsTime = function(strVal) {
        var hours, minutes;
        if (strVal.length != 5 || strVal.substring(2, 3) != ":") return false;
        //saat kysmy
        hours = strVal.substring(0, 2);
        if (isNaN(hours) == true) { return false; }
        if (hours.substring(0, 1) == '.' || hours.substring(1, 2) == '.') return false;
        if ((parseInt(hours) >= 0 && parseInt(hours) < 24) == false) return false;
        //dakika kysmy
        minutes = strVal.substring(3, 5);
        if (isNaN(minutes) == true) return false;
        if (minutes.substring(0, 1) == '.' || minutes.substring(1, 2) == '.') return false;
        if ((parseInt(minutes) >= 0 && parseInt(minutes) < 60) == false) return false;
        return true;
    }
    //IsNumeric
    this.IsNumeric = function(val) {
        if (val == null) return false
        var ValidChars = "0123456789.", Char;
        if (val == '') return false;
        for (i = 0; i < val.length; i++) {
            Char = val.charAt(i);
            if (ValidChars.indexOf(Char) == -1) return false;
        }
        return true;
    }
    this.cNumeric = function(val) {
        if (this.IsNumeric(val)) return val
        return 0
    }
    //min ve max gelmeyebilir
    this.CheckNumeric = function(val, min, max) {
        if (!this.IsNumeric(val)) return false
        if (this.IsNumeric(min)) {
            if (val < min) return false
        }
        if (this.IsNumeric(max)) {
            if (val > max) return false
        }
        return true
    }
    // dd/mm/yyyy
    this.ToDate = function(argDateStr) {
        var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
        var matchArray = argDateStr.match(datePat); // is the format ok?	
        day = matchArray[1];
        month = matchArray[3];
        year = matchArray[5];
        return new Date(month + '/' + day + '/' + year);
    }
    this.DateToStr = function(argDate) {
        var xDay = MY.datePart('d', argDate), xMon = MY.datePart('m', argDate);
        if (xDay < 10) xDay = '0' + xDay;
        if (xMon < 10) xMon = '0' + xMon;
        return xDay + '/' + xMon + '/' + MY.datePart('yyyy', argDate)
    }
    //dateadd
    this.dateAdd = function(p_Interval, p_Number, p_Date) {
        if (isNaN(p_Number)) { return "invalid number: '" + p_Number + "'"; }

        p_Number = new Number(p_Number);
        var dt = new Date(p_Date);
        switch (p_Interval.toLowerCase()) {
            case "yyyy": 
                {// year
                    dt.setFullYear(dt.getFullYear() + p_Number);
                    break;
                }
            case "q": 
                {		// quarter
                    dt.setMonth(dt.getMonth() + (p_Number * 3));
                    break;
                }
            case "m": 
                {		// month
                    dt.setMonth(dt.getMonth() + p_Number);
                    break;
                }
            case "y": 	// day of year
            case "d": 	// day
            case "w": 
                {		// weekday
                    dt.setDate(dt.getDate() + p_Number);
                    break;
                }
            case "ww": 
                {	// week of year
                    dt.setDate(dt.getDate() + (p_Number * 7));
                    break;
                }
            case "h": 
                {		// hour
                    dt.setHours(dt.getHours() + p_Number);
                    break;
                }
            case "n": 
                {		// minute
                    dt.setMinutes(dt.getMinutes() + p_Number);
                    break;
                }
            case "s": 
                {		// second
                    dt.setSeconds(dt.getSeconds() + p_Number);
                    break;
                }
            case "ms": 
                {		// second
                    dt.setMilliseconds(dt.getMilliseconds() + p_Number);
                    break;
                }
            default: 
                {
                    return "invalid interval: '" + p_Interval + "'";
                }
        }
        return dt;
    }
    //datepart
    this.datePart = function(p_Interval, p_Date) {
        var dtPart = new Date(p_Date);
        switch (p_Interval.toLowerCase()) {
            case "yyyy": return dtPart.getFullYear();
            case "q": return parseInt(dtPart.getMonth() / 3) + 1;
            case "m": return dtPart.getMonth() + 1;
            case "y": return dateDiff("y", "1/1/" + dtPart.getFullYear(), dtPart); 		// day of year
            case "d": return dtPart.getDate();
            case "w": return dtPart.getDay(); // weekday
            case "ww": return dateDiff("ww", "1/1/" + dtPart.getFullYear(), dtPart); 	// week of year
            case "h": return dtPart.getHours();
            case "n": return dtPart.getMinutes();
            case "s": return dtPart.getSeconds();
            case "ms": return dtPart.getMilliseconds(); // millisecond	// <-- extension for JS, NOT available in VBScript
            default: return "invalid interval: '" + p_Interval + "'";
        }
    }


    this.cmb_empty = function(cmb) {
        //Clears the state combo box contents.	    	    
        for (var count = cmb.options.length - 1; count > -1; count--) {
            cmb.options[count] = null;
        }
        return true
    }
    this.cmb_add = function(cmb, val, str) {
        cmb.options[cmb.options.length] = new Option(str, val);
        return true
    }
    this.replaceAll = function(txt, replace, with_this) {
        return txt.replace(new RegExp(replace, 'g'), with_this);
    }
    /* ---------------------------------------------------------------------- *\
    UC_text
    \* ---------------------------------------------------------------------- */
    var _objectsTEXT
    this.TEXT = function(objectId) {
        this.TEXT.Get = function() {
            //alz('F')          
            if (!_objectsTEXT) return
            for (var i = 0; i < _objectsTEXT.length; i++) {
                if (_objectsTEXT[i].objectId == objectId) return _objectsTEXT[i];
            }
            return
        }
        //initialize
        this.TEXT.Init = function(argIsMultiLang, argLangSep, argDefLangCode_InArray, argTextMode, argAllLangNames, preWarning, imageList, maxlength) {
            if (!_objectsTEXT) _objectsTEXT = new Array();
            var _new = new TEXT_Init(objectId, argIsMultiLang, argLangSep, argDefLangCode_InArray, argTextMode, argAllLangNames, preWarning, imageList, maxlength)
            _objectsTEXT[_objectsTEXT.length] = _new
            return _new
        }
        //objects
        this.TEXT_objects = _objectsTEXT;
        return this.TEXT;
    }

    function TEXT_Init(objectId, argIsMultiLang, argLangSep, argDefLangCode_InArray, argTextMode, argAllLangNames, preWarning, imageList, maxlength) {
        this.objectId = objectId;
        this.IsMultiLang = argIsMultiLang;
        this.SEP = argLangSep;
        this.DefLangCode_InArray = argDefLangCode_InArray;
        this.TextMode = argTextMode;
        this.AllLangNames = argAllLangNames;
        this.preWarning = preWarning;
        this.imageList = imageList;
        this.maxlength = (maxlength ? maxlength : 0);
        //
        var txtALLVALS = $('#' + this.objectId + '_TXTAllVal');
        var txtDEF_JQ;
        if (this.TextMode == 3) {//EDITOR             
            this.IsTiny = true;
            $('.txtNormalA').ckeditor();
            //$('#'+this.objectId+'_TXT').ckeditor(); // böyle olursa bir önceki yok oluyor, mecburen clas'dan gideceğiz ve document.readyde
            //config buttons, her seferde yapacak ama olsun
            CKEDITOR.config.skin = 'office2003';
            CKEDITOR.config.toolbarStartupExpanded = false;
            CKEDITOR.config.toolbar = [ //'Image','Flash'
                ['Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript', 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
                ['Link', 'Unlink', 'Table', 'HorizontalRule', 'Font', 'FontSize', 'TextColor', 'BGColor'], '/',
                ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'SpellChecker', 'Scayt'],
                ['Undo', 'Redo', '-', 'Find', 'Replace', '-', 'Source', 'Preview', 'Templates', 'Print', 'Maximize']
            ];

            //set blur
            CKEDITOR.instances[this.objectId + '_TXT'].on('blur', function(e) {
                this.updateElement();
                $('#' + this.name).trigger('blur');
            });
        } else {
            this.IsTiny = false;
            txtDEF_JQ = $('#' + this.objectId + '_TXT');
        }
        //sub functions               
        this.TextGet = function() { //default obje value, tiny veya $Query            
            if (this.IsTiny)
                return CKEDITOR.instances[this.objectId + '_TXT'].getData();
            else
                return txtDEF_JQ.val();
        }
        this.TextSet = function(value) { //default obje value, tiny veya $Query            
            if (this.IsTiny)
                CKEDITOR.instances[this.objectId + '_TXT'].setData(value);
            else
                txtDEF_JQ.val(value);
            return true
        }
        //sadece default girilen text maxlength'den fazla mı diye bakar, zaten diğerlerini açılan popouptan kontrol ediyoruz
        this.IsValid = function() {
            if (this.maxlength == 0) return true
            var val = this.TextGet()
            if (val.length > this.maxlength) return false
            return true
        }
        this.Serialize = function() {
            var lcRet = ''
            var lcArr = txtALLVALS.val().split(this.SEP); //all old data
            for (var i = 0; i < lcArr.length; i++) {
                if (i == this.DefLangCode_InArray) {
                    lcRet += this.TextGet(); //default data, (text entry may change)
                } else {
                    lcRet += lcArr[i]
                }
                if (i < lcArr.length - 1) lcRet += this.SEP //except last one
            }
            return lcRet
        }
        //
        this.DeSerialize = function(datas) {
            txtALLVALS.val(datas)
            var lcArr = datas.split(this.SEP);
            this.TextSet(lcArr[this.DefLangCode_InArray]); //default show data
            //
            this.ShowWarnings();
        }
        this.Show = function() {
            $('#' + this.objectId + '_TXT').show();
            $('#cmdText' + this.objectId + ', #spnMsg' + this.objectId).show();
        }
        this.Hide = function() {
            $('#' + this.objectId + '_TXT').hide();
            $('#cmdText' + this.objectId + ', #spnMsg' + this.objectId).hide();
        }
        //
        this.ShowWarnings = function() {
            $('#spnMsg' + this.objectId).html('');
            var lcMessage = ''
            var lcArrNames = this.AllLangNames.split(this.SEP);
            var lcArr = txtALLVALS.val().split(this.SEP); //all data            
            for (var i = 0; i < lcArr.length; i++) {
                if (lcArr[i] == '') {
                    //Sistemde tanımlı olmayanlar için mesaj çıkmasın
                    if (i < lcArrNames.length) lcMessage += (lcMessage == '' ? '' : ',') + lcArrNames[i];
                }
            }
            if (lcMessage != '') {
                $('#spnMsg' + this.objectId).html('<br /><b>' + preWarning + '</b> : ' + lcMessage);
            }
        }
        //ilk seferde henüz hiç data olmayabilri. O zaman tamamına missing yazsın diye default val set edelim
        if (this.IsMultiLang) {
            var lcalldata = txtALLVALS.val()
            if (lcalldata == '') {
                var lcArrNames = this.AllLangNames.split(this.SEP);
                for (var i = 0; i < lcArrNames.length; i++) { lcalldata += this.SEP }
                txtALLVALS.val(lcalldata);
            }
            this.ShowWarnings();
        }
    }
    /* ---------------------------------------------------------------------- *\
    UC_dat için 
    \* ---------------------------------------------------------------------- */
    this.DAT = function(objectId) {
        return Init_DAT(this, objectId)
    }
    function Init_DAT(parent, objectId) {
        this.IsValid = function() {
            return parent.IsDate(this.RetVal())
        }
        this.RetVal = function() {
            if (this.IsCheckShow() && !this.IsChecked()) return RetValDefNull()
            return $('#' + objectId + '_txtDate').val();
        }
        this.SetVal = function(value) {
            $('#' + objectId + '_txtDate').val(value);
            if (!this.IsCheckShow()) return
            //set checkbox
            if (value == RetValDefNull()) {
                this.CheckBoxSet(false)
            } else {
                this.CheckBoxSet(true)
            }
        }
        this.RetValDate = function() {
            var dtStr = this.RetVal();
            return parent.ToDate(dtStr)
        }
        this.SetValDate = function(value) {
            $('#' + objectId + '_txtDate').val(parent.DateToStr(value))
        }
        this.focus = function() {
            $('#' + objectId + '_txtDate').focus();
        }
        this.IsChecked = function() {
            if (this.IsCheckShow()) {
                if ($('#' + objectId + '_chkDate').is(':checked')) return true
            }
            return false
        }
        this.IsCheckShow = function() {
            return $('#' + objectId + '_chkDate').length == 1
        }
        this.CheckBoxSet = function(val) {
            if (!this.IsCheckShow()) return
            $('#' + objectId + '_chkDate').attr('checked', val)
            //chekbox varsa ve checkli degilse disable 
            if (this.IsCheckShow() && !this.IsChecked()) this.SetDisable()
            else this.SetEnable()

        }
        this.SetEnable = function() {
            $('#' + objectId + '_txtDate').datepicker('enable');
            $('#' + objectId + '_txtDate').removeAttr('readonly')
        }
        this.SetDisable = function() {
            $('#' + objectId + '_txtDate').datepicker('disable');
            $('#' + objectId + '_txtDate').attr('readonly', 'readonly')
        }
        this.SetNoOfMonths = function(value) {
            $('#' + objectId + '_txtDate').datepicker('option', 'numberOfMonths', value);
        }
        function RetValDefNull() {
            return $('#' + objectId + '_hidDefNullVal').val()
        }
        this.IsNull = function() {
            return (RetVal() == RetValDefNull())
        }
        return this;
    }
    /* ---------------------------------------------------------------------- *\
    UC_Air için 
    \* ---------------------------------------------------------------------- */
    var _objectsAIR
    this.AIR = function(objectId) {
        this.AIR.Get = function() {
            //alz('F')          
            if (!_objectsAIR) return
            for (var i = 0; i < _objectsAIR.length; i++) {
                if (_objectsAIR[i].objectId == objectId) return _objectsAIR[i];
            }
            return
        }
        //initialize
        this.AIR.Init = function(countryId) {
            if (!_objectsAIR) _objectsAIR = new Array();
            var _new = new AIR_Init(objectId, countryId)
            _objectsAIR[_objectsAIR.length] = _new
            return _new
        }
        //objects
        this.AIR_objects = _objectsAIR;
        return this.AIR;
    }

    function AIR_Init(objectId, countryId) {
        this.objectId = objectId;
        this.CountryId = countryId
        var xMe = this
        //        
        var txtDEF_JQ = $('#' + this.objectId + '_TXT');
        var hidVAL_JQ = $('#' + this.objectId + '_hidVal');
        var hidVALCNTISO_JQ = $('#' + this.objectId + '_hidCntIso');

        var ac_ExtraParams = "'argCountryId':'" + this.CountryId + "'"
        txtDEF_JQ.autocomplete("Service_UcAir.asmx/SearchAirports", {
            minChars: 0,
            width: txtDEF_JQ.width() + 100,
            dataType: 'json', matchCase: true, ExtraParams: ac_ExtraParams,
            httpMethod: 'POST',
            contentType: 'application/json; charset=utf-8',
            autoFill: false,
            formatItem: function(row, i, max) {
                var rowx = row[0].split('$');
                if (parseInt(rowx[0]) < 0)
                    return '<img src="images/city.png" />' + rowx[1];
                else
                    return '&nbsp;&nbsp;&nbsp;<img src="images/plane.png" />' + rowx[1];
            },
            formatMatch: function(row, i, max) {
                return row[0].split('$')[1]
            },
            formatResult: function(row) {
                return row[0].split('$')[1]
            }
        });
        txtDEF_JQ.result(function(event, data, formatted) {
            var row = data[0].split('$')
            hidVAL_JQ.val(row[0]);
            hidVALCNTISO_JQ.val(row[2]);
            xMe.OnAutoCompleteSelected(xMe.RetBaseAreaId());
        });
        //sub functions       
        this.IsValid = function() {
            return hidVAL_JQ.val() != '';
        }
        this.IsAirport = function() {
            return parseInt(hidVAL_JQ.val()) > 0;
        }
        this.IsRegion = function() {
            return parseInt(hidVAL_JQ.val()) < 0;
        }
        this.RetVal = function() {
            return hidVAL_JQ.val();
        }
        this.RetText = function() {
            return txtDEF_JQ.val();
        }
        this.RetCountryIso = function() {
            return hidVALCNTISO_JQ.val();
        }
        this.RegionId = function() {
            var ret = 0
            if (this.IsRegion()) ret = this.RetVal() * -1
            return ret
        }
        this.AirportId = function() {
            var ret = 0
            if (this.IsAirport()) ret = this.RetVal()
            return ret
        }
        this.RetBaseAreaId = function() {
            //CountryId & "$" & AirportId & "$" & RegionId & "$" & ResortId, new object
            return '0$' + this.AirportId() + '$' + this.RegionId() + '$0'
        }
        this.OnAutoCompleteSelected = function(BaseAreaId) {
            //overridable
        }
        this.focus = function() {
            return txtDEF_JQ.focus();
        }
        this.CloneVal = function(air) {
            hidVAL_JQ.val(air.RetVal());
            hidVALCNTISO_JQ.val(air.RetCountryIso());
            txtDEF_JQ.val(air.RetText());
        }
    }

}
