// JavaScript Document

function showMessage()
{
	document.getElementById("app_message").innerHTML = "";
	document.getElementById('app_message').style.display = 'block';
}

function hideMessage()
{
	document.getElementById('app_message').style.display = 'none';
}

function trim(string)
{
    return string.replace(/(^\s+)|(\s+$)/g, "");
}

function checkEmailAddress(emailStr)
{
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (filter.test(trim(emailStr))) {
		return true;
	}
	return false;
}

function confirm_delete() {
	if (confirm('Are you sure?')) {
			return true;
	} else {
			return false;
	}
}

//#####################################################################################################

function priceFormat(value)
{
 	var ValueStr = new String( parseFloat(value) );
	if (ValueStr == "NaN") ValueStr = "0";

	var ind = ValueStr.lastIndexOf(".");
	// xxxx.xx
	if ( ind >= 0 )
	{
		if ( ind == ValueStr.length - 2 )
		{
			ValueStr += "0";
		}

		if ( ind < ValueStr.length - 3 )
		{
			ValueStr = ValueStr.substr(0, ind + 3);
		}
	}
	else
	{
		ValueStr += ".00";
	}
	// xxxx.xx

	// x,xxx.xx
	ind = ValueStr.lastIndexOf(".");
	if ( ind >= 4 )
	{
		ValueStr = ValueStr.substr(0, ind - 3) + "," + ValueStr.substr(ind - 3, 6);
	}
	// x,xxx.xx
	return ValueStr;
}

//#####################################################################################################

function loadurl(url, obj_output)
{
	$.ajax({
		type: "POST",
		url: url,
		dataType: "html",
		complete: function(){},
		success: function(data){
			if (obj_output == null) obj_output = 'listing';
			$('#'+obj_output).html(data);
		},
		error: function()
		{
			//alert('Export operation failed!');
		}
	});
}

function checkEmail(sEmail)
{
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (filter.test(sEmail)) {
		return true;
	}
	return false;
}

/* Custom selects */
(function($){
 $.fn.extend({

 	customStyle : function(options) {
          var classStyle = 'customStyle';
          if (options) classStyle = options;

	  if(!$.browser.msie || ($.browser.msie&&$.browser.version>6)){
	  return this.each(function() {

            $(this).wrap('<div class="'+classStyle+'SelectBoxWrapper"/>');
            var selectBoxSpanWrapper = $(this).parent();
            //selectBoxSpanWrapper.css('width', $(this).css(width));

            //calculate selected text size
            $('body').append('<div id="calcSize" class="calcSize" style="display:none;width:auto;white-space: nowrap;font-size:'+selectBoxSpanWrapper.css('font-size')+';">'+$(this).find(':selected').text()+'</div>');
            var textWidth = $('#calcSize').width();
            var textHeight = $('#calcSize').height();
            $('.calcSize').remove();

            //TODO:
            //indian hotfox
            if (textWidth < 10) textWidth = $(this).find(':selected').text().length * 6;

            $(this).after('<span class="'+classStyle+'SelectBoxInner">'+$(this).find(':selected').text()+'</span>').css({position:'absolute', opacity:0,fontSize:selectBoxSpanWrapper.css('font-size')});
            $(this).css('border', '0');
            $(this).css('height', textHeight + 'px');
            $(this).css('width', textWidth + 'px');

            //set new select width
            var selectBoxWrapperWidth = selectBoxSpanWrapper.width() + parseInt(selectBoxSpanWrapper.css('padding-right'));
            if (textWidth < selectBoxWrapperWidth) $(this).css('width', selectBoxWrapperWidth + 'px');

            //set new select height
            var selectBoxWrapperHeight = selectBoxSpanWrapper.height() + parseInt(selectBoxSpanWrapper.css('padding-top')) + parseInt(selectBoxSpanWrapper.css('padding-bottom'));
            if (textHeight < selectBoxWrapperHeight) $(this).css('height', selectBoxWrapperHeight + 'px');

            var selectBoxSpanInner = $(this).next();

            if ($.browser.msie)
            {
                $(this).mouseover(function(){
                    $(this).addClass('width-auto');
                });

                $(this).blur(function(){
                    $(this).removeClass('width-auto');
                });
            }

            $(this).change(function(){
                $('body').append('<span id="calcSize" class="calcSize" style="display:none;font-size:'+selectBoxSpanWrapper.css('font-size')+'">'+$(this).find(':selected').text()+'</span>');
                var textWidth = $('#calcSize').width();
                var textHeight = $('#calcSize').height();
                $('.calcSize').remove();

                selectBoxSpanInner.text($(this).find(':selected').text());

                $(this).css('border', '0');
                $(this).css('height', textHeight + 'px');
                $(this).css('width', textWidth + 'px');

                //set new select width
                var selectBoxWrapperWidth = selectBoxSpanWrapper.width() + parseInt(selectBoxSpanWrapper.css('padding-right'));
                if (textWidth < selectBoxWrapperWidth) $(this).css('width', selectBoxWrapperWidth + 'px');

                //set new select height
                var selectBoxWrapperHeight = selectBoxSpanWrapper.height() + parseInt(selectBoxSpanWrapper.css('padding-top')) + parseInt(selectBoxSpanWrapper.css('padding-bottom'));
                if (textHeight < selectBoxWrapperHeight) $(this).css('height', selectBoxWrapperHeight + 'px');

            });

	  });
	  }
	}
 });
})(jQuery);

function badFixSelectBoxDataWidthIE() {
    if ($.browser.msie) {
        $('select').each(function() {
            if($(this).attr('multiple') == false) {
                $(this).mousedown(function() {
                    if($(this).css("width") != "auto") {
                        var width = $(this).width();
                        $(this).data("origWidth", $(this).css("width")).css("width", "auto");

                        // If the width is now less than before then undo
                        if($(this).width() < width) {
                            $(this).unbind('mousedown');
                            $(this).css("width", $(this).data("origWidth"));
                        }
                    }
                })

                // Handle blur if the user does not change the value
                .blur(function() {
                    $(this).css("width", $(this).data("origWidth"));
                })

                // Handle change of the user does change the value
                .change(function() {
                    $(this).css("width", $(this).data("origWidth"));
                });
            }
        });
    }
}



(function($) {
    $.fn.lazyLoadFBLike = function(options) {
        var settings = {
            threshold: 0,
            failurelimit: 0,
            effect: "show",
            container: window
        };
        if (options) {
            $.extend(settings, options);
        }
        var elements = this;

        $(settings.container).bind("scroll", function(event) {
            var counter = 0;
            elements.each(function() {
                if ($.abovethetop(this, settings) || $.leftofbegin(this, settings)) {}
                else if (!$.belowthefold(this, settings) && !$.rightoffold(this, settings)) {
                    $(this).trigger("appear");
                } else {
                    if (counter++ > settings.failurelimit) {
                        return false;
                    }
                }
            });
            var temp = $.grep(elements, function(element) {
                return !element.loaded;
            });
            elements = $(temp);
        });

        this.each(function() {
            var self = this;
            $(self).one("appear", function() {
                if (!this.loaded) {
                    $(this).show().html('<iframe src="http://www.facebook.com/plugins/like.php?href=' + $('span',this).text() + '&amp;layout=button_count&amp;show_faces=false&amp;width=450&amp;action=like&amp;font&amp;colorscheme=light&amp;height=35" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:35px;" allowTransparency="true"></iframe>');
                    self.loaded = true;
                };
            });
        });
        $(settings.container).trigger("scroll");
        return this;
    };
    $.belowthefold = function(element, settings) {
        if (settings.container === undefined || settings.container === window) {
            var fold = $(window).height() + $(window).scrollTop();
        } else {
            var fold = $(settings.container).offset().top + $(settings.container).height();
        }
        return fold <= $(element).offset().top - settings.threshold;
    };
    $.rightoffold = function(element, settings) {
        if (settings.container === undefined || settings.container === window) {
            var fold = $(window).width() + $(window).scrollLeft();
        } else {
            var fold = $(settings.container).offset().left + $(settings.container).width();
        }
        return fold <= $(element).offset().left - settings.threshold;
    };
    $.abovethetop = function(element, settings) {
        if (settings.container === undefined || settings.container === window) {
            var fold = $(window).scrollTop();
        } else {
            var fold = $(settings.container).offset().top;
        }
        return fold >= $(element).offset().top + settings.threshold + $(element).height();
    };
    $.leftofbegin = function(element, settings) {
        if (settings.container === undefined || settings.container === window) {
            var fold = $(window).scrollLeft();
        } else {
            var fold = $(settings.container).offset().left;
        }
        return fold >= $(element).offset().left + settings.threshold + $(element).width();
    };
})(jQuery);


function blockStandart(element) {
    if ($(element+' .blockUI').size() == 0 )
    {
        $(element).block({
                            message: '',
                            css: {
                                    backgroundColor: '#fff',
                                    color: '#000',
                                    top:'1%',
                                    left:'1%',
                                    width:'100px'
                            },
                            overlayCSS:  {
                                backgroundColor: '#fff',
                                opacity:         0.6
                            },
                            centerY: false,
                            centerX: false
                    });
    }
}

function blockInvisible(element) {
    if ($(element+' .blockUI').size() == 0 )
    {
        $(element).block({
            overlayCSS:  {backgroundColor: 'transparent'},
            message: ''
        });
    }
}

//same as popupWindow() but more correct without height parameter
//use this function only
function showPopupYoutube(nWidth, data){

	$('#modalContent').html("");
	$('#modalPreloader').css('display', 'block');
	if (nWidth > 0){
		//block screen
		$('body').block({
            message: $('#modalWindow'),
            //centerY: true,
            overlayCSS: { backgroundColor: '#000000' },
            opacity: 0.5,
            css:
            {
                top: getBodyScrollTop() + 40,
                left: ($(window).width() - nWidth) /2 + 'px',
                width: nWidth + 'px'
            }
        });
    }


    $(".blockOverlay").css('position','fixed').css('height',$(window).height());

    //get contents
    $.ajax({
        type: "POST",
        url: data,
        dataType: "html",
        complete: function(){},
        success: function(response){
            $('#modalPreloader').css('display', 'none');
			$('#modalContent').append('<div class="div_left"></div>');
            $('#modalContent .div_left').html(response);
			var g_temp_top = ($(window).height() - $('#modalContent .div_left').height())/2;
			g_temp_top = (g_temp_top > 0)? g_temp_top: 40;
			$('#modalWindow').css('width',$('#modalContent .div_left').width()).css({
				'left' : -($('#modalContent .div_left').width()/2),
				'top' : (g_temp_top),
				'margin-bottom': '40px'
			});
        },
        complete: function(){
			$("#modalContent").prepend('<div class="pos_abs r-10 wrapper_modal"><a class="close_but r-20" href="#">&nbsp;</a></div>');
			$('a.close_but').attr('title','Click to close').click(hidePopupYoutube);
            $('.blockOverlay').attr('title','Click to close').click(hidePopupYoutube);
        }
    });

}

function hidePopupYoutube()
{
    $('#modalContent').html("");
    $('body').unblock();
}

function getBodyScrollTop()
{
	return self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
}

/* JSON parser */
(function($){$.toJSON=function(o)
{if(typeof(JSON)=='object'&&JSON.stringify)
return JSON.stringify(o);var type=typeof(o);if(o===null)
return"null";if(type=="undefined")
return undefined;if(type=="number"||type=="boolean")
return o+"";if(type=="string")
return $.quoteString(o);if(type=='object')
{if(typeof o.toJSON=="function")
return $.toJSON(o.toJSON());if(o.constructor===Date)
{var month=o.getUTCMonth()+1;if(month<10)month='0'+month;var day=o.getUTCDate();if(day<10)day='0'+day;var year=o.getUTCFullYear();var hours=o.getUTCHours();if(hours<10)hours='0'+hours;var minutes=o.getUTCMinutes();if(minutes<10)minutes='0'+minutes;var seconds=o.getUTCSeconds();if(seconds<10)seconds='0'+seconds;var milli=o.getUTCMilliseconds();if(milli<100)milli='0'+milli;if(milli<10)milli='0'+milli;return'"'+year+'-'+month+'-'+day+'T'+
hours+':'+minutes+':'+seconds+'.'+milli+'Z"';}
if(o.constructor===Array)
{var ret=[];for(var i=0;i<o.length;i++)
ret.push($.toJSON(o[i])||"null");return"["+ret.join(",")+"]";}
var pairs=[];for(var k in o){var name;var type=typeof k;if(type=="number")
name='"'+k+'"';else if(type=="string")
name=$.quoteString(k);else
continue;if(typeof o[k]=="function")
continue;var val=$.toJSON(o[k]);pairs.push(name+":"+val);}
return"{"+pairs.join(", ")+"}";}};$.evalJSON=function(src)
{if(typeof(JSON)=='object'&&JSON.parse)
return JSON.parse(src);return eval("("+src+")");};$.secureEvalJSON=function(src)
{if(typeof(JSON)=='object'&&JSON.parse)
return JSON.parse(src);var filtered=src;filtered=filtered.replace(/\\["\\\/bfnrtu]/g,'@');filtered=filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']');filtered=filtered.replace(/(?:^|:|,)(?:\s*\[)+/g,'');if(/^[\],:{}\s]*$/.test(filtered))
return eval("("+src+")");else
throw new SyntaxError("Error parsing JSON, source is not valid.");};$.quoteString=function(string)
{if(string.match(_escapeable))
{return'"'+string.replace(_escapeable,function(a)
{var c=_meta[a];if(typeof c==='string')return c;c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16);})+'"';}
return'"'+string+'"';};var _escapeable=/["\\\x00-\x1f\x7f-\x9f]/g;var _meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};})(jQuery);

/*
	Watermark v3.1.3 (March 22, 2011) plugin for jQuery
	http://jquery-watermark.googlecode.com/
	Copyright (c) 2009-2011 Todd Northrop
	http://www.speednet.biz/
	Dual licensed under the MIT or GPL Version 2 licenses.
*/
(function(a,h,y){var w="function",v="password",j="maxLength",n="type",b="",c=true,u="placeholder",i=false,t="watermark",g=t,f="watermarkClass",q="watermarkFocus",l="watermarkSubmit",o="watermarkMaxLength",e="watermarkPassword",d="watermarkText",k=/\r/g,s="input:data("+g+"),textarea:data("+g+")",m="input:text,input:password,input[type=search],input:not([type]),textarea",p=["Page_ClientValidate"],r=i,x=u in document.createElement("input");a.watermark=a.watermark||{version:"3.1.3",runOnce:c,options:{className:t,useNative:c,hideBeforeUnload:c},hide:function(b){a(b).filter(s).each(function(){a.watermark._hide(a(this))})},_hide:function(a,r){var p=a[0],q=(p.value||b).replace(k,b),l=a.data(d)||b,m=a.data(o)||0,i=a.data(f);if(l.length&&q==l){p.value=b;if(a.data(e))if((a.attr(n)||b)==="text"){var g=a.data(e)||[],c=a.parent()||[];if(g.length&&c.length){c[0].removeChild(a[0]);c[0].appendChild(g[0]);a=g}}if(m){a.attr(j,m);a.removeData(o)}if(r){a.attr("autocomplete","off");h.setTimeout(function(){a.select()},1)}}i&&a.removeClass(i)},show:function(b){a(b).filter(s).each(function(){a.watermark._show(a(this))})},_show:function(g){var p=g[0],u=(p.value||b).replace(k,b),h=g.data(d)||b,s=g.attr(n)||b,t=g.data(f);if((u.length==0||u==h)&&!g.data(q)){r=c;if(g.data(e))if(s===v){var m=g.data(e)||[],l=g.parent()||[];if(m.length&&l.length){l[0].removeChild(g[0]);l[0].appendChild(m[0]);g=m;g.attr(j,h.length);p=g[0]}}if(s==="text"||s==="search"){var i=g.attr(j)||0;if(i>0&&h.length>i){g.data(o,i);g.attr(j,h.length)}}t&&g.addClass(t);p.value=h}else a.watermark._hide(g)},hideAll:function(){if(r){a.watermark.hide(m);r=i}},showAll:function(){a.watermark.show(m)}};a.fn.watermark=a.fn.watermark||function(p,o){var t="string";if(!this.length)return this;var s=i,r=typeof p===t;if(r)p=p.replace(k,b);if(typeof o==="object"){s=typeof o.className===t;o=a.extend({},a.watermark.options,o)}else if(typeof o===t){s=c;o=a.extend({},a.watermark.options,{className:o})}else o=a.watermark.options;if(typeof o.useNative!==w)o.useNative=o.useNative?function(){return c}:function(){return i};return this.each(function(){var B="dragleave",A="dragenter",z=this,i=a(z);if(!i.is(m))return;if(i.data(g)){if(r||s){a.watermark._hide(i);r&&i.data(d,p);s&&i.data(f,o.className)}}else{if(x&&o.useNative.call(z,i)&&(i.attr("tagName")||b)!=="TEXTAREA"){r&&i.attr(u,p);return}i.data(d,r?p:b);i.data(f,o.className);i.data(g,1);if((i.attr(n)||b)===v){var C=i.wrap("<span>").parent(),t=a(C.html().replace(/type=["']?password["']?/i,'type="text"'));t.data(d,i.data(d));t.data(f,i.data(f));t.data(g,1);t.attr(j,p.length);t.focus(function(){a.watermark._hide(t,c)}).bind(A,function(){a.watermark._hide(t)}).bind("dragend",function(){h.setTimeout(function(){t.blur()},1)});i.blur(function(){a.watermark._show(i)}).bind(B,function(){a.watermark._show(i)});t.data(e,i);i.data(e,t)}else i.focus(function(){i.data(q,1);a.watermark._hide(i,c)}).blur(function(){i.data(q,0);a.watermark._show(i)}).bind(A,function(){a.watermark._hide(i)}).bind(B,function(){a.watermark._show(i)}).bind("dragend",function(){h.setTimeout(function(){a.watermark._show(i)},1)}).bind("drop",function(e){var c=i[0],a=e.originalEvent.dataTransfer.getData("Text");if((c.value||b).replace(k,b).replace(a,b)===i.data(d))c.value=a;i.focus()});if(z.form){var w=z.form,y=a(w);if(!y.data(l)){y.submit(a.watermark.hideAll);if(w.submit){y.data(l,w.submit);w.submit=function(c,b){return function(){var d=b.data(l);a.watermark.hideAll();if(d.apply)d.apply(c,Array.prototype.slice.call(arguments));else d()}}(w,y)}else{y.data(l,1);w.submit=function(b){return function(){a.watermark.hideAll();delete b.submit;b.submit()}}(w)}}}}a.watermark._show(i)})};if(a.watermark.runOnce){a.watermark.runOnce=i;a.extend(a.expr[":"],{data:function(c,d,b){return!!a.data(c,b[3])}});(function(c){a.fn.val=function(){var e=this;if(!e.length)return arguments.length?e:y;if(!arguments.length)if(e.data(g)){var f=(e[0].value||b).replace(k,b);return f===(e.data(d)||b)?b:f}else return c.apply(e,arguments);else{c.apply(e,arguments);a.watermark.show(e);return e}}})(a.fn.val);p.length&&a(function(){for(var b,c,d=p.length-1;d>=0;d--){b=p[d];c=h[b];if(typeof c===w)h[b]=function(b){return function(){a.watermark.hideAll();return b.apply(null,Array.prototype.slice.call(arguments))}}(c)}});a(h).bind("beforeunload",function(){a.watermark.options.hideBeforeUnload&&a.watermark.hideAll()})}})(jQuery,window);


function loadLazyImages()
{
    $('.lazy_image:visible').each(function() {
        if (isOnScreen($(this)) || isMobileClient()) //iphone is not support
        {
            var obj = $(this);
            obj.removeClass('lazy_image');

            var img = new Image();
            img.onload = function() { obj.attr('src', img.src); }
            img.src = obj.attr('data');
        }
    });
}

function isOnScreen(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = elem.offset().top; //iphone bug
    var elemBottom = elemTop + elem.height();
    //alert(elemBottom +'>='+docViewTop+' '+elemTop+'<='+docViewBottom);
    return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
}

function isMobileClient()
{
    CFMOBI_IS_PAGE = false;
    var CFMOBI_TOUCH = ["iPhone","iPod","Android","BlackBerry9530","LG-TU915 Obigo","LGE VX","webOS"];
    for (var i = 0; i < CFMOBI_TOUCH.length; i++) {
        if (navigator.userAgent.indexOf(CFMOBI_TOUCH[i]) != -1) {
            return true;
        }
    }

    return false;
}


