﻿/*
*			Z-Form Validation ver:3.0
*			Copyright 2011 ZJSoft Technologies
*			http://www.zjsoftech.com
*			Email: jashsoftpk@aim.com, support@zjsoftech.com
*
*/

function dumpProps(obj, parent) {
    // Go through all the properties of the passed-in object 
   for (var i in obj) {
       // if a parent (2nd parameter) was passed in, then use that to 
      // build the message. Message includes i (the object's property name) 
      // then the object's property value on a new line 
      if (parent) { var msg = parent + "." + i + "\n" + obj[i]; } else { var msg = i + "\n" + obj[i]; }
       // Display the message. If the user clicks "OK", then continue. If they 
      // click "CANCEL" then quit this level of recursion 
      if (!confirm(msg)) { return; }
       // If this property (i) is an object, then recursively process the object 
      if (typeof obj[i] == "object") { 
         if (parent) { dumpProps(obj[i], parent + "." + i); } else { dumpProps(obj[i], i); }
       }
    }
 };
 
(function($) {
    $.extend({
        code: function(length, special) {
            var iteration = 0;
            var password = "";
            var randomNumber;
            if (length == undefined) {
                var length = 8;
            }
            if (special == undefined) {
                var special = false;
            }
            while (iteration < length) {
                randomNumber = (Math.floor((Math.random() * 100)) % 94) + 33;
                if (!special) {
                    if ((randomNumber >= 33) && (randomNumber <= 47)) { continue; }
                    if ((randomNumber >= 58) && (randomNumber <= 64)) { continue; }
                    if ((randomNumber >= 91) && (randomNumber <= 96)) { continue; }
                    if ((randomNumber >= 123) && (randomNumber <= 126)) { continue; }
                }
                iteration++;
                password += String.fromCharCode(randomNumber);
            }
            return password;
        }
    });

    $.fn.overlapPanel = function(options) {
        var merged_options = $.extend({}, $.defaults, options);
        $('div' + merged_options.scope).find('div.plOverlap').css({
            'position': 'absolute',
            'z-index': '535',
            'display': 'none',
            'width': $('div' + merged_options.scope).find('div.plOverlapCaller').width()
        });
        $('div' + merged_options.scope).find('div.plOverlapCaller').css({
            'cursor': 'pointer',
            'z-index': '535'
        });
        $(this).unbind('click');
        $('div' + merged_options.scope).find('div.plOverlap :submit').unbind('click');
        $(this).click(function() {
            $('div' + merged_options.scope).find('div.plOverlap').slideToggle('slow');
            return false;
        });
        $('div' + merged_options.scope).find('div.plOverlap :submit').click(function() {
            $('div' + merged_options.scope).find('div.plOverlap').slideToggle('slow');
            return true;
        });
    };
    $.fn.zjForm = function(options) {
        var merged_options = $.extend({}, $.defaults, options);
        $('div' + merged_options.scope).find('div.mask').css({
            'background-color': merged_options.maskBGColor,
            'position': 'absolute',
            'z-index': '525',
            'display': 'none',
            'opacity': '0.4',   //transparency for FF
            'filter': 'alpha(opacity=40)'   //transparency for IE
        });
        $('div' + merged_options.scope).find('div.maskdialog').css({
            'width': merged_options.dialogWidth + 'px',
            'height': merged_options.dialogHeight + 'px',
            'background-color': merged_options.dialogBGColor,
            'padding': merged_options.dialogPadding,
            'position': 'absolute',
            'z-index': '526',
            'display': 'none'
        });
        
        $(this).unbind('click');
        $(window).unbind('resize');
        $(window).unbind('scroll');
        
        $(this).click(function() {
            
            if ($(document).find('div.plOverlap')) {
                $(document).find('div.plOverlap').slideUp('slow');
            }
            if (merged_options.dialogMessage != '') {
                $('div' + merged_options.scope).find('div.maskdialog').html(merged_options.dialogMessage);
            }

            $(window).resize(function() {
                $.resize(options);
            });
            $(window).scroll(function() {
                $.resize(options);
            });
            $.resize(options);
            //$('#mask').fadeIn(1000);

            $('div' + merged_options.scope).find('div.mask').fadeTo("slow", 0.8);

            $('div' + merged_options.scope).find('div.maskdialog').fadeIn(2000);
            
            //UNCOMMENT BELOW TO INCLUDE WITH FORM VALIDATOR
            var result = $.formValidator(options);
		
	    if (result) {
		if (merged_options.submitFormURL!='' && merged_options.submitForm!='' && merged_options.submitFormReturn!=''){
                    $.post(merged_options.submitFormURL, $('form' + merged_options.submitForm).serialize(), function(data){
                        if(data==1){
                            $(document).find(merged_options.submitFormReturn).html(merged_options.successMsg);
                        }else{
                            $(document).find(merged_options.submitFormReturn).html(data);
                        }
                        $.unLoad(options);
                        $.scrollTo('div'+merged_options.submitFormReturn,800);
                    });
                }
            }else{
                $.unLoad(options);
                alert("Fill all the required fields properly.");
                $.scrollTo('form'+merged_options.submitForm,800);
            }
            /*if (merged_options.submitFormURL!='' && merged_options.submitForm!='' && merged_options.submitFormReturn!=''){
                    $.post(merged_options.submitFormURL, $('form' + merged_options.submitForm).serialize(), function(data){
                        if(data==1){
                            $(document).find(merged_options.submitFormReturn).html(merged_options.successMsg);
                        }else{
                            $(document).find(merged_options.submitFormReturn).html(data);
                        }
                        $.unLoad(options);
                    });
            }*/
            return false;
        });

    };
    $.unLoad = function(options) {
        var merged_options = $.extend({}, $.defaults, options);
        $('div' + merged_options.scope).find('div.mask').hide();
        $('div' + merged_options.scope).find('div.maskdialog').hide();
    };
    $.fn.zjForm.unLoad = function(options) {
        var merged_options = $.extend({}, $.defaults, options);
        $('div' + merged_options.scope).find('div.mask').hide();
        $('div' + merged_options.scope).find('div.maskdialog').hide();
    };

    $.resize = function(options) {
        var merged_options = $.extend({}, $.defaults, options);

        var scrolledX = window.pageXOffset ? window.pageXOffset : document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft;
        var scrolledY = window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
        var centerX = self.innerWidth ? self.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth;
        var centerY = self.innerHeight ? self.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
        $('div' + merged_options.scope).find('div.mask').css({ 'width': centerX + 'px', 'height': centerY + 'px' });
        $('div' + merged_options.scope).find('div.mask').css({ 'top': scrolledY + 'px', 'left': scrolledX + 'px' });
        //alert($('#dialog').width());
        //$('#dialog').css('top', (scrolledY + (centerY - $('#dialog').height()) / 2) + "px");
        //$('#dialog').css('left', (scrolledX + (centerX - $('#dialog').width()) / 2) + "px");
        $('div' + merged_options.scope).find('div.maskdialog').css('top', (scrolledY + (centerY - merged_options.dialogHeight) / 2) + "px");
        $('div' + merged_options.scope).find('div.maskdialog').css('left', (scrolledX + (centerX - merged_options.dialogWidth) / 2) + "px");
        if ($('div' + merged_options.scope).find('div.maskdialog')[0]) {
            $('div' + merged_options.scope).find('div.maskdialog')[0].oncontextmenu = function() { return false; };
            $('div' + merged_options.scope).find('div.mask')[0].oncontextmenu = function() { return false; };
        }
    };
    
    
    $.formValidator = function (options) {
		
		// merge options with defaults
		var merged_options = $.extend({}, $.defaults, options);
		
		// result boolean
		var boolValid = true;
		
		// result error message
		var errorMsg = '';
		
		// clean errors
		$(merged_options.submitForm + ' .error-both, ' + merged_options.submitForm + ' .error-same, ' + merged_options.submitForm + ' .error-input').removeClass('error-both').removeClass('error-same').removeClass('error-input');
		
		// gather inputs & check is valid
                
		$(merged_options.submitForm+' .req-email:visible, '+merged_options.submitForm+' .req-telephone:visible, '+merged_options.submitForm+' .req-string:visible, '+merged_options.scope+' .req-same:visible, '+merged_options.scope+' .req-both:visible, '+merged_options.scope+' .req-numeric:visible, '+merged_options.scope+' .req-date:visible, '+merged_options.scope+' .req-min:visible').each(function() {
			thisValid = $.formValidator.validate($(this),merged_options);
			boolValid = boolValid && thisValid.error;
                        
			if (!thisValid.error) {
				errorMsg  = thisValid.message;//alert(merged_options.req_invalidImg);
				if(this.type=='radio')
					($(this).prev('img').length)?$(this).css({'border-color':'#BB6666', 'color':'#660000', 'background-color':'#FFEFEF'}).prev('img').attr('src',merged_options.req_invalidImg):$(this).css({'border-color':'#BB6666', 'color':'#660000', 'background-color':'#FFEFEF'})//.before('<img src="'+merged_options.req_invalidImg+'">').css('vertical-align','top');
				else
					($(this).next('img').length)?$(this).css({'border-color':'#BB6666', 'color':'#660000', 'background-color':'#FFEFEF'}).next('img').attr('src',merged_options.req_invalidImg):$(this).css({'border-color':'#BB6666', 'color':'#660000', 'background-color':'#FFEFEF'})//.after('<img src="'+merged_options.req_invalidImg+'">').css('vertical-align','top');
			}else{
				if(this.type=='radio')
					($(this).prev('img').length)?$(this).css({'border-color':'', 'color':'', 'background-color':''}).prev('img').attr('src',merged_options.validatedImg):$(this).css({'border-color':'', 'color':'', 'background-color':''})//.before('<img src="'+merged_options.validatedImg+'">').css('vertical-align','top');
				else
					($(this).next('img').length)?$(this).css({'border-color':'', 'color':'', 'background-color':''}).next('img').attr('src',merged_options.validatedImg):$(this).css({'border-color':'', 'color':'', 'background-color':''})//.after('<img src="'+merged_options.validatedImg+'">').css('vertical-align','top');
			}
		});
		
		// submit form if there is and valid
		if ((merged_options.submitForm != '') && boolValid) {
			if ($(merged_options.errorDiv).length){
                            $(merged_options.errorDiv).fadeOut();
                        }
		}
		
		// if there is errorMsg print it if it is not valid
		if (!boolValid && errorMsg != '') {
			if ($(merged_options.errorDiv).length){
                            var tempErr = (merged_options.customErrMsg != '') ? merged_options.customErrMsg : errorMsg;
                            $(merged_options.errorDiv).hide().html(tempErr).fadeIn();
                        }
		}
		
		return boolValid;
	};
	
	$.formValidator.validate = function(obj,opts) {
		obj.val($.formValidator.validate.trim(obj.val()));
		var valAttr = obj.val();
		var css = opts.errorClass;
		var mail_filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		var numeric_filter = /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)|(^-?\d*$)/;
		var telephone_filter = /^([0-9\+\- ]{10,})+$/;
		var tmpresult = true;
		var result = true;
		var errorTxt = '';
		
		if(obj.hasClass('radio')) {
			if(obj.attr('type')=='text'||obj.attr('type')=='textarea') {
				if($(opts.scope+' input.radio[name='+obj.attr('rel')+'][rel='+obj.attr('rel')+']:checked').length) {
					// REQUIRED FIELD VALIDATION
					if (obj.hasClass('req-string')) {
						tmpresult = (valAttr != '');
						if (!tmpresult) errorTxt = opts.errorMsg.reqString;
						result = result && tmpresult;
					}
					// TELEPHONE VALIDATION
					if (obj.hasClass('req-telephone')) {
						tmpresult = telephone_filter.test(valAttr);
						if (!tmpresult) errorTxt = (valAttr == '') ? opts.errorMsg.reqTelEmpty : opts.errorMsg.reqTelNotValid;
						result = result && tmpresult;
					}
					// E-MAIL VALIDATION
					if (obj.hasClass('req-email')) {
						tmpresult = mail_filter.test(valAttr);
						if (!tmpresult) errorTxt = (valAttr == '') ? opts.errorMsg.reqMailEmpty : opts.errorMsg.reqMailNotValid;
						result = result && tmpresult;
					}
					// DATE VALIDATION
					if (obj.hasClass('req-date')) {
						
						tmpresult = true;
						
						var arr = valAttr.split(opts.dateSeperator);
						var curDate = new Date();
						
						if (valAttr == '') {
							
							tmpresult = true;
						} else {
							
							if (arr.length < 3) {
								tmpresult = false;
							} else {
								tmpresult = (arr[0] <= 12) && (arr[1] <= 31) && (arr[2] <= curDate.getFullYear());
							}
						}
						
						if (!tmpresult) errorTxt = opts.errorMsg.reqDate;
						result = result && tmpresult;
					}
					// MINIMUM REQUIRED FIELD VALIDATION
					if (obj.hasClass('req-min')) {
						tmpresult = (valAttr.length >= obj.attr('minlength'));
						if (!tmpresult) errorTxt = opts.errorMsg.reqMin.replace('%1',obj.attr('minlength'));
						result = result && tmpresult;
					}
					// NUMERIC FIELD VALIDATION
					if (obj.hasClass('req-numeric')) {
						tmpresult = numeric_filter.test(valAttr);
						if (!tmpresult) errorTxt = opts.errorMsg.reqNum;
						result = result && tmpresult;
					}
				}
			}else{
				tmpresult = ($(opts.scope+' input.radio[name='+obj.attr('name')+']:checked').length!=0);
				if(tmpresult) {
					if (obj.hasClass('req-both')) {
						group = $(opts.scope+' input.radio[name='+obj.attr('name')+']').attr('rel');
						$(opts.scope+' .req-both[rel="'+group+'"]').each(function() {
							if( $(this).val() == '') {
								tmpresult = false;
							}
						});
						if (!tmpresult) {
							$(opts.scope+' .req-both[rel="'+group+'"]').parent().parent().addClass('error-both');
							errorTxt = opts.errorMsg.reqBoth;
						} else {
							$(opts.scope+' .req-both[rel="'+group+'"]').parent().parent().removeClass('error-both');
						}
					}
				}
			}
			result = result && tmpresult;
		}else{
		// REQUIRED FIELD VALIDATION
		if (obj.hasClass('req-string')) {
			tmpresult = (valAttr != '');
			if(obj.hasClass('captcha') && tmpresult){
				tmpresult = $.formValidator.validate.captcha(valAttr);
			}
			if (!tmpresult) errorTxt = opts.errorMsg.reqString;
			result = result && tmpresult;
		}
		// SAME FIELD VALIDATION
		if (obj.hasClass('req-same')) {
			
			tmpresult = true;
			
			group = obj.attr('rel');
			tmpresult = true;
			$(opts.scope+' .req-same[rel="'+group+'"]').each(function() { 
				if($(this).val() != valAttr || valAttr == '') {
					tmpresult = false;
				}
			});
			if (!tmpresult) {
				$(opts.scope+' .req-same[rel="'+group+'"]').parent().parent().addClass('error-same');
				errorTxt = opts.errorMsg.reqSame;
			} else {
				$(opts.scope+' .req-same[rel="'+group+'"]').parent().parent().removeClass('error-same');
			}
			
			result = result && tmpresult;
		}
		// BOTH INPUT CHECKING
		// if one field entered, the others should too.
		if (obj.hasClass('req-both')) {
			
			tmpresult = true;
			
			if (valAttr != '') {
				
				group = obj.attr('rel');

				$(opts.scope+' .req-both[rel="'+group+'"]').each(function() { 
					if($(this).val() == '') {
						tmpresult = false;
					}
				});
				
				if (!tmpresult) {
					$(opts.scope+' .req-both[rel="'+group+'"]').parent().parent().addClass('error-both');
					errorTxt = opts.errorMsg.reqBoth;
				} else {
					$(opts.scope+' .req-both[rel="'+group+'"]').parent().parent().removeClass('error-both');
				}
			}
			
			result = result && tmpresult;
		}
		// TELEPHONE VALIDATION
		if (obj.hasClass('req-telephone')) {
			tmpresult = telephone_filter.test(valAttr);
			if (!tmpresult) errorTxt = (valAttr == '') ? opts.errorMsg.reqTelEmpty : opts.errorMsg.reqTelNotValid;
			result = result && tmpresult;
		}
		// E-MAIL VALIDATION
		if (obj.hasClass('req-email')) {
			tmpresult = mail_filter.test(valAttr);
			if (!tmpresult) errorTxt = (valAttr == '') ? opts.errorMsg.reqMailEmpty : opts.errorMsg.reqMailNotValid;
			result = result && tmpresult;
		}
		// DATE VALIDATION
		if (obj.hasClass('req-date')) {
			
			tmpresult = true;
			
			var arr = valAttr.split(opts.dateSeperator);
			var curDate = new Date();
			
			if (valAttr == '') {
				
				tmpresult = true;
			} else {
				
				if (arr.length < 3) {
					tmpresult = false;
				} else {
					tmpresult = (arr[0] <= 12) && (arr[1] <= 31) && (arr[2] <= curDate.getFullYear());
				}
			}
			
			if (!tmpresult) errorTxt = opts.errorMsg.reqDate;
			result = result && tmpresult;
		}
		// MINIMUM REQUIRED FIELD VALIDATION
		if (obj.hasClass('req-min')) {
			tmpresult = (valAttr.length >= obj.attr('minlength'));
			if (!tmpresult) errorTxt = opts.errorMsg.reqMin.replace('%1',obj.attr('minlength'));
			result = result && tmpresult;
		}
		// NUMERIC FIELD VALIDATION
		if (obj.hasClass('req-numeric')) {
			tmpresult = numeric_filter.test(valAttr);
			if (!tmpresult) errorTxt = opts.errorMsg.reqNum;
			result = result && tmpresult;
		}
		}
		if (result) {
			obj.removeClass(css);
		} else {
			obj.addClass(css);
		}
		
		return {
			error: result,
			message: errorTxt
		};
	};
	
	$.formValidator.validate.trim = function(str) {
		var str = str.replace(/^\s\s*/, ''),ws = /\s/,i = str.length;
		while (ws.test(str.charAt(--i)));
		return str.slice(0, i + 1);
	};
	
	$.formValidator.validate.captcha = function(str) {
		var validCaptcha = false;
		$.get('CAPTCHA_process_form.php',
			  {'zCaptchaCode_req':str},
			  function(data) {
				validCaptcha = data;
			  });
		return validCaptcha;
	};
    $.defaults = {
        scope: '',
        dialogWidth: '170',
        dialogHeight: '25',
        dialogPadding: '20px',
        dialogBGColor: '#ccc',
        dialogMessage: '',
        maskBGColor: '#000',
        submitForm: '',
        submitFormReturn: '',
        submitFormURL: '',
        errorClass: 'error-input',
        errorDiv: '#warn',
        invalidImg:	'/images/ajax/invalid.gif',
	req_invalidImg:	'/images/ajax/req_invalid.gif',
	requiredImg:	'/images/ajax/required.gif',
	editingImg:	'',
	validatedImg:	'/images/ajax/validated.gif',
        successMsg: '',
        errorMsg		: 	{
								reqString		:	'Gerekli alanları doldurun',
								reqDate			:	'Tarih geçerli <b>değil</b>!',
								reqNum			:	'Sadece sayı girebilirsiniz',
								reqTelEmpty		:	'Telephone empty',
								reqTelNotValid	:	'Telephone number is not valid',
								reqMailNotValid	:	'E-mail geçerli <b>değil</b>!',
								reqMailEmpty	:	'E-mail girin',
								reqSame			:	'Tekrar alanları aynı <b>değil</b>!',
								reqBoth			:	'İlgili alanları doldurmalısınız!',
								reqMin			:	'Minimum %1 karakter girmelisiniz'
							},
        customErrMsg: ''    //one error msg for all
    };
})(jQuery);
