var url;var animation = false;var path;var canClose = false;var currentPicture;var totalPictures;var focus = "";var newsletterCity = "";var preloadedImgs = {};jQuery.fn.center = function () {    this.centerX();    this.centerY();    return this;}jQuery.fn.centerX = function () {    /*if(false) {        var left = ( $(window).width() - this.outerWidth() ) / 2+$(window).scrollLeft();        alert(        "window.width "+$(window).width()+"\n"+        "this.outerWidth "+this.outerWidth()+"\n"+        "window.scrollLeft "+$(window).scrollLeft()+"\n"+        "left "+left        );        this.css("position","absolute");        this.css("left", left + "px");      } else {*/    this.css("position","absolute");    var left = ( $(window).width() - this.outerWidth() ) / 2+$(window).scrollLeft();    this.css("left", left + "px");            return this;}jQuery.fn.centerY = function () {    this.css("position","absolute");    var top = ( $(window).height() - this.outerHeight() ) / 2;    if(top<5) top = 5;    top += +$(window).scrollTop();    this.css("top",  top+"px");    return this;}function displayPartner(id) {    //console.log("displaying partner with id "+id);    if(parseInt(id)==id) {        location.href="/p/"+id;    } else {        location.href="/"+id;    }    /*$.get(path+"index.php?ajax&partner="+id, function(response) {        showDialog(response, {width: "auto"}, function() {                    });    });*/}function showDialog(content, css, callback) {    $("#dialogContent").html(content);                if(!$.browser.msie) {		if(css!=undefined) {			$("#dialog").css(css).center().css(css);     		} else {			$("#dialog").center();		}    } else {        if(css!=undefined)            if(css!=null) {                //if(css["width"]=='auto') css["width"] = "500px";                $("#dialog").css(css);            }                        $("#dialog").css( {"position":"absolute", "top":($(window).scrollTop() + 50) +"px", "left":"100px"});    }                    var docheight = $(document).height();    $("#overlay").css('height', docheight+'px').show(200, function() {    	if($.browser.msie)    		$("#overlay").css("filter", "alpha(opacity = 40)");    	        $("#dialog").fadeIn(300, function() {            $(document).bind("keyup.myEvents", function(e) {              if (e.keyCode == 27) {closeDialog();}   // esc key            });            canClose = true;            if($.isFunction(callback)) callback();                    });    });    }function closeDialog() {    canClose = false;    $(document).unbind("keyup.myEvents");    $("#dialog").fadeOut(300, function() {        $("#dialogContent").html("");        $("#overlay").fadeOut(100);    });}function showGallery(object, objectid, picnumber, download) {    var winHeight = parseInt($(window).height());    var post = {object: object, objectid: objectid, picnumber: picnumber, windowheight: winHeight};    if(download==true) post["download"] = 1;    else post["download"] = 0;    $.post(path+"index.php?ajax&showGallery", post, function (response) {        currentPicture = picnumber+1;        showDialog(response, {width: 'auto', top:($(window).scrollTop()+15)+'px'}, function() {totalPictures = parseInt($("#total").html());showPic("pic"+(picnumber+1));});    });}function downloadImg(anchor) {    var url = path+"download.php?f="+encodeURIComponent($('#currentpicture').attr('src'));    $(anchor).attr("href", url);}function offerAPartner() {    $.get(path+"index.php?ajax&offerapartner", function (response) {        showDialog(response, {width: 'auto'}, function() {            init_defaulttext();            var container = $(".offerapartner");            container.find(".submit").click(function() {                var partner = container.find(".text").val();                var city = container.find(".selectbox").val();                if(partner!=""&&partner!=container.find(".text").attr("title")) {                    $.post(path+"index.php?ajax&submitapartner", {partner: partner, city: city}, function(response) {                        container.hide();                        $("#success").show();                        setTimeout("closeDialog();", 2500);                    });                } else {                    alert("Nepalikite neužpildytų laukų!");                    container.find(".text").focus();                }            });        });    });}function nav(direction) {    if(totalPictures>1) {        var navTo, go;        if(direction=="left") { // navigate left            if(currentPicture==1) navTo = totalPictures;            else navTo = currentPicture-1;            go = -1;        } else { // navigate right            if(currentPicture==totalPictures) navTo = 1;            else navTo = currentPicture+1;            go = 1;        }        currentPicture = navTo;        $("#current").html(currentPicture);        showPic("pic"+currentPicture);        for(var i=1; i<=3; i++ ) {            preloadPic("pic"+(navTo+go*i));        }                       //console.log("navigating to "+direction+", showing picture "+currentPicture);    }}function preloadPic(picid) {    var pic = $("#"+picid);    if(pic.length>0) {        var tmp = new Image(pic.attr("width"), pic.attr("height"));        tmp.src = pic.val();                }}function showPic(fieldid) {    var pic = $("#"+fieldid);    if(pic.length == 1) {        var currpic = $("#currentpicture");        //currpic.css("background", "#FFFFFF");        if($.browser.msie) {            var data = eval('(' + pic.attr("title") + ')');            $("#dialog").width(data.width+90);            currpic.attr("src","").attr("src", pic.val())            .width(data.width)            .height(data.height)            //.height(pic.attr("height"))            ;        }        else {            currpic.attr("src","").attr("src", pic.val()).css({"width": pic.attr("width")+"px", "height": pic.attr("height")+"px"});        }                $("#dialog").centerX();                //preloader        /*var img = new Image();        img.onload=function() {            var left = (currpic.width()-pic.attr("width"))/2;            currpic.attr("src",pic.val()).css({ "width": pic.attr("width")+"px", "height": pic.attr("height")+"px" });                    };        img.src=pic.val();*/            }}function scroll(direction, clicker) {    var parentdiv = $(clicker).parent().parent().parent();    if(!animation) {        var scroller = parentdiv.find(".picscroller");        var left = parseInt(scroller.css("left"));        var wrapperWidth = parentdiv.find(".picwrapper").width();        var scrollerWidth = scroller.find("table").width();        var picWidth = scroller.find("td:first").width();        var speed = 300;        //console.log("direction: "+direction+", current left attr: "+left+", wrapperWidth: "+wrapperWidth+", scrollerWidth: "+scrollerWidth);            if(direction=="left") { /* moving left */            if( left <= ((-1)*picWidth) ) {                animation = true;                left = left+picWidth;                scroller.animate({left: left+"px"}, speed, function() {animation = false;});                //console.log("moving left");            } else {                //console.log("no need to move left");            }        } else { /* moving right */            if( wrapperWidth < (scrollerWidth+left) ) {                animation = true;                left = left-picWidth;                scroller.animate({left: left+"px"}, speed, function() {animation = false;});                //console.log("moving right");            } else {                //console.log("no need to move right");            }        }        if(wrapperWidth >= (scrollerWidth+left)) {            //hide right movement            //console.log("hiding right");            parentdiv.find(".navright").hide();         } else {            //console.log("showing right");            parentdiv.find(".navright").show();         }        if(left > ((-1)*picWidth)) {            //console.log("hiding left");            parentdiv.find(".navleft").hide();             //hide left        } else {            //console.log("showing left");            parentdiv.find(".navleft").show();         }        //console.log("end");    }        }function registerIncredible() {    var post = {};    $(".incredible").each(function () {        post[$(this).attr("name")] = $(this).val();    });    $.post(path+"index.php?ajax&registerIncredible", post, function(response) {        showDialog(response, undefined, undefined);    });}function showRegisterForm() {    $.get(path+"index.php?ajax&registerform", function (response) {            showDialog(response, {width: 'auto'}, function() {            $('#registerform').submit(function() {                  return false;            });                        }, "Gauk išskirtinius pasiūlymus ir informaciją apie pačias geriausias nuolaidas!");    });}function registerStep(step) {    var registerform = $("#registerform");        var errordiv = registerform.find("div.error");        if(step==2) {      //console.log('Handler for .submit() called.');      var error = "";      var emptyfields = false;      registerform.find(".field").each(function() {          if($(this).val()=="") {              emptyfields = true;              $(this).addClass("error");          } else if($(this).hasClass("error")) {              $(this).removeClass("error");          }      });                  if(emptyfields) error += "Nepalikite tuščių laukų.<br />";                              var email = $("#email").val();      var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;        if( email!="" && !emailPattern.test(email) ) {          error += "Blogai įvestas el. pašto adresas.<br />";          $("#email").addClass("error");      }            if( $("#password").val()!="" ) {          if( $("#password").val().length<5 ) {              error += "Slaptažodis turi būti 5 arba daugiau simbolių ilgio.<br />";              $("#password").addClass("error");          } else if( $("#password").val().length>32 ) {              error += "Slaptažodis turi būti mažiau nei 32 simbolių ilgio.<br />";              $("#password").addClass("error");                                    } else if($("#password").val()!=$("#passwordagain").val() ) {              error += "Nesutampa slaptažodžiai.<br />";              $("#password").addClass("error");              $("#passwordagain").addClass("error");          }      }      if(error!="") {          errordiv.html(error).slideDown(300);      } else {          $("#step1").hide();          $("#step2").show();      }      } else if(step==1) {          $("#step1").show();          $("#step2").hide();      } else if(step==3) {        if(!$("#agree").attr("checked")) {            alert("Privalote sutikt gauti Daily Card naujienas.");            return false;        }                var post = {};        registerform.find(".field").each(function() {              post[$(this).attr("name")] = $(this).val();        });                  post["birthday"] = $("#byear").val() + "-" + $("#bmonth").val() + "-" + $("#bday").val();        var groups = "";        $(".groups").each(function() {            groups += (groups=="" ? "" : ", ")+$(this).val();        });        post["groups"] = groups;        $.post("index.php?ajax&reguser", post, function(response) {          if(response=="") {              registerform.find(".wrapper").slideUp("fast");              registerform.find(".success").slideDown("fast");          } else {              errordiv.html(response).slideDown(300);          }      });    }}function check(what, source) {    //console.log(what + " " + source)    var checked;    if(what=="all") {        $('.groups, .cat input').attr('checked', $(source).attr('checked') );    } else if(what=="single") {        checked = true;        $(source).parent().parent().find(".subcat input").each(function() {            if(!$(this).attr("checked")) checked = false;        });        $(source).parent().parent().find(".cat input").attr("checked", checked);    } else {        $('.'+what).attr('checked', $(source).attr('checked') );    }    if(!$(source).attr("checked")) {        $("#all input").attr("checked",false);    } else {        checked = true;        $('.subcat input').each(function() {if(!$(this).attr("checked")) checked = false;});        if(checked) $("#all input").attr("checked",true);    }}function showGetCardForm(element) {    $.get(path+"index.php?ajax&getCardForm", function (response) {        var init_func = function() {            init_checkboxes();            $("#getcardform").submit(function() {                var form = $(this);                if(!$("#agree").attr("checked")) {                    alert("Privalote sutikti, kad su jumis susisiektų banko darbuotojas.");                    return false;                }                var emptyfield=false;                var post = {};                form.find(".field").each(function() {                    if($(this).val()=="") emptyfield = true;                    post[$(this).attr("name")] = $(this).val();                });                post["isclient"] = $("#isclient").attr("checked") ? "1" : "0";                if(emptyfield) {                    alert("Nepalikite tuščių laukų!");                    return false;                            }                                $.post("index.php?ajax&getCard", post, function(response) {                      if(response=="") {                          form.find(".wrapper").slideUp("fast");                          form.find(".success").slideDown("fast");                      } else {                          form.find(".error").html(response).slideDown(300);                      }                      //console.log(response);                                      });                   return false;                       });        };        if(element == undefined) {            showDialog(response, {width: 'auto'}, init_func, "Anketa kortelei gauti");        } else {            $(element).html(response);            init_func();        }                            });}function forgotPassForm() {    $.get(path+"index.php?ajax&forgotpassform", function (response) {        showDialog(response, {width: 'auto'}, function() {            $("#passreset .submit").click(function() {                $.get(path+"index.php?ajax&resetpass="+$("#email").val(), function(response) {                    var div = $("#passreset");                    if(response!="") {                        div.find("div.error").html(response).slideDown("fast");                    } else {                          div.find(".wrapper").slideUp("fast");                          div.find(".success").slideDown("fast");                    }                });            });        });            });}function init_defaulttext() {    $(".default").focus(function() {        if($(this).val()==$(this).attr("title")) {            $(this).val('');            $(this).removeClass("shadow");        }    }).blur(function() {        if($(this).val()==''||$(this).val()==$(this).attr("title")) {            $(this).addClass("shadow");            $(this).val($(this).attr("title"));        }    }).blur();       $("form:not(.ignore)").submit(function() {        $(this).find(".default").each(function() {            if($(this).val()==$(this).attr("title")) {                $(this).val(''); $(this).removeClass("shadow");            }        });    });}function init_checkboxes() {    $('input[type=checkbox]').each(function() {        $(this).wrap(function() {            return ($(this).is(':checked')) ? '<span class="custom_checkbox selected" />' : '<span class="custom_checkbox" />';        });    });        $('.custom_checkbox input[type=checkbox]').click(function () {        if($(this).hasClass("distinct")) {            $(".custom_checkbox input[name='"+$(this).attr("name")+"']").attr("checked", false).parent().removeClass("selected");            $(this).attr("checked", true).parent().addClass("selected");        } else {            $(this).parent().toggleClass('selected');        }    });    }function sectionSwitch(to, self) {    $('.ab').hide();    $('#'+to).show();}function login() {    var post = {name: $("#loginpartner").val(), contract: $("#logincontract").val()};    $.post(path+"index.php?ajax&login", post, function(response) {        if(response=="login") {            location.href=path+"partneriams";        } else {            alert(response);        }    });}function logout() {    $.get("index.php?ajax&logout=1", function() {        location.reload();    });}function link(whereto) {    location.href = path+whereto;}function createDropDown(source) {    var selected = source.find("option[selected]");    if(selected.length==0) selected = source.find("option:first-child");    var options = $("option", source);        var targetid = 'target'+source.attr("id");    source.hide();    source.after('<dl id="'+targetid+'" class="dropdown"></dl>')    var target = $("#"+targetid);    var text = selected.html();    if(selected.attr("class")!=undefined) text = "<span class='"+selected.attr("class")+"'>"+text+"</span>";    target.append('<dt><a href="#">' + text +         '<span class="value">' + selected.val() +         '</span></a></dt>');    target.append('<dd><ul></ul></dd>')    options.each(function(){    var text = $(this).html();    if($(this).attr("class")!=undefined) text = "<span class='"+$(this).attr("class")+"'>"+text+"</span>";                target.find("dd ul").append('<li><a href="#">' +             text + '<span class="value">' +             $(this).val() + '</span></a></li>');    });        target.find("dt a").click(function(e) {        target.find("dd ul").toggle();        e.preventDefault();    });        $(document).bind('click', function(e) {        var clicked = $(e.target);        if (! clicked.parents().hasClass("dropdown"))            $(".dropdown dd ul").hide();    });                    target.find("dd ul li a").click(function(e) {        var text = $(this).html();        target.find("dt a").html(text);        target.find("dd ul").hide();                source.val($(this).find("span.value").html())        e.preventDefault();            });            }function init_newtemplate() {    clock.init(".clock");        // dailyheader solution    var sect = $(".leftborder.section");    if(sect.length>0 && !($.browser.msie && parseInt($.browser.version, 10) <= 7) ) {        var totalCities = $(".dailyheader .cityy").length;        var totalDailyCities = $(".dailyheader .section:not(.leftborder) .cityy").length;        var prevSect = sect.prevAll(".section");        var prevWidth = prevSect.width();        var parentWidth = sect.parent().width();        var offset = ( parseInt(sect.css("padding-left")) + parseInt(sect.css("margin-left")) + 6 );        var newWidth = (parentWidth-prevWidth)-offset;        if( totalDailyCities > 2 && totalDailyCities/totalCities > 0.5 ) {            newWidth = parseInt(parentWidth/2)-offset;            prevSect.css("width", (parentWidth-newWidth-offset)+"px");        }        sect.css({"width": newWidth+"px", "float":"right"});        prevSect.css("height", sect.height()+"px");    }            // tooltip init    $(".tooltip").hover(function() {        var self = $(this);        self.nextAll(".thetooltip").show().position({            "my":"middle top",            "at":"middle bottom",            "of":self        });    }, function() {        $(this).nextAll(".thetooltip").hide();    });        // newsletter/partner popup from header init    $(".popupcontainer").each(function() {        var parent = $(this);        var title = parent.find(".title");        var popup = parent.find(".popup");        var toggle = parent.find(".toggle");        var parentId = parent.attr("id");        var uniqueClassName = 'popup'+parentId;        parent.find(".trigger").click(function(e) {            //console.log("clicked on "+parentId);            var trigger = $(this);            e.preventDefault();            if(popup.is(":visible")) {                $(document).unbind("click."+uniqueClassName);                toggle.hide();                title.removeClass("selected");            } else {                var first = true;                $(document).bind("click."+uniqueClassName, function(e) {                    if(first) first = false;                    else {                        var target = $(e.target);                        if( title!=target  && title.find(target).length == 0 && popup != target && popup.find(target).length == 0 && target.closest(".ui-autocomplete").length == 0  ) {                            //console.log("clicked elsewhere for parent "+parentId, "target", e.target, "found", popup.find(target));                            $(document).unbind("click."+uniqueClassName);                            toggle.hide();                            title.removeClass("selected");                                                    }                    }                });                title.addClass("selected");                toggle.show();                var offset = (popup.width()/2 - 200) * (-1);                if(parentId=="social") {                    title.position({                        my:"left top",                        at:"left top",                        offset:"-2px 5px",                        of:parent                    });                                    offset = "-63";                }                popup.position({                    my:"center top",                    at:"center bottom",                    offset: (offset+" -1"),                    of:title                });            }                    });    });        // init select    $("select").each(function() {        createDropDown($(this));    });        // slide show blocks    $(".slideshow").each(function() {        $self = $(this);        var href = $self.attr("href");        $self.find("li").click(function() {        	localhref = $(this).attr("href");        	if(localhref!=undefined) location.href = localhref;        	else location.href = href;        });        var slideshow = $(this);        var parent = $(this).parent();        var pid = parent.attr("id");        slideshow.serialScroll({            items:'li',            prev:"#"+pid+" .prev",            next:"#"+pid+" .next",            offset:0, //when scrolling to photo, stop 230 before reaching it (from the left)            start:0, //as we are centering it, start at the 2nd            duration:1200, // Length of the animation (if you scroll 2 axes and use queue, then each axis take half this time)            force:true, // Force a scroll to the element specified by 'start' (some browsers don't reset on refreshes)            stop:true, // Each click will stop any previous animations of the target. (false by default)            lock:false, // Ignore events if already animating (true by default)            cycle:true, // pull back once you reach the end            //easing:'easeOut' //use this easing equation for a funny effect            constant:false,            exclude:2,            easing:'easeOutQuart', //use this easing equation for a funny effect            //jump: true,            interval:4000        });        parent.find(".navigation").click(function() {            slideshow.trigger('stop');        });    });        // top menu selection highlight    url = $("#url").val();    path = $("#path").val();    var selected = null;    $("#menu a").each(function(){        var self = $(this);        if(self.attr("href")==url) {            self.addClass("selected");            selected = self;        }    });        if($("#submenu").length == 1) {    	$("#content").css("padding-top", 0);//(parseInt(sub.css("padding-bottom"))+cPadTop)+"px");    	if(selected!=null) {            $("#submenu .toCenter").position({                of:selected,                at:"center bottom",                my:"center top",                offset:"0 1"            });    	    	} else {    		$("#submenu .toCenter").hide();    	}    	    }                    if($("#single").length>0) {        s = $("#single");        var done = false;        var hidden;        var left = s.find(".left");        var right = s.find(".right");        do {            hidden = null;            hidden = left.find(".newsthumbbig:hidden:first");            if(hidden.length>0) {                if(left.height()+hidden.height()<right.height()) {                    hidden.show();                } else {                    done = true;                }            } else {                done = true;            }            //done = true;        } while (!done);                       /*var newW = 600;        $(".youtube").each(function() {            var self = $(this);            var oldW = self.width();            var oldH = self.height();                 self.mouseenter(function() {                self.find("embed, object").css({ width: newW+"px", height:oldH*newW/oldW+"px" });            }).mouseleave(function() {                self.find("embed, object").css({ width: oldW+"px", height:oldH+"px" });                            });            self.find(".expand").click(function(e) {                self.find("embed, object").css({ width: newW+"px", height:oldH*newW/oldW });                e.preventDefault();                $(this).find(",text").toggle();            });        });*/    }                  // init faq    $("li.selected .answer").show();                                                          // init mega category dropdown    $(".cat").each(function() {    	var parent = $(this);    	var field = parent.find(".catfield");    	var caption = parent.find(".catcaption")    	var dropdown = parent.find(".catdropdown");    	caption.click(function() {    		dropdown.slideToggle(300);    	});    	dropdown.find("a").click(function(e) {    		e.preventDefault();    		field.val($(this).attr("name"));    		parent.closest("form").submit();    	});    	/*        var head = $("#catmegadropdown .header");        $("#catmegadropdown").show();        var toEllip = $("#catselected .inner .txt");        if(toEllip.find(".shadow").length == 0) {            toEllip.add(head).autoEllipsis({ellipsis : "...", addEllipsisAnyway : false});        }        $("#catmegadropdown").hide();        $(this).find(".toggles").click(function() {            $("#catmegadropdown").slideToggle(400);            $(".toggles").toggleClass("selected");            var left = $("#catselected").offset().left - head.offsetParent().offset().left;            head.css("left", left+"px");        });        $(this).find("a").click(function(e) {            $("#catfield").val( $(this).attr("name") );            //$("#cat .txt").html(  );            e.preventDefault();            $(this).closest("form").submit();        });*/    });        // partner init     var partner = $("#partner");    if(partner.length==1) {        GMap.init(".markers");        var bottom = $("#bottom");        partner.find(".about p img, .about div > img").each(function() {        	$(this).remove();        	//$(this).appendTo(bottom);        	/* FIXME check partner descriptions for images and fix this after */        });        partner.find(".about p, .about div").each(function() {        	var self = $(this);        	if($.trim(self.text()).length==0) {        		self.remove();        	}        });    }            // hoverable objects - general buttons, hoverables    $(".button, .hoverable").mouseenter(function() {        $(this).addClass("hover");    }).mouseleave(function() {        $(this).removeClass("hover");    });        // general validation fields (email, phone)    $(".email, #email, .phone").each(function() {        $(this).change(function() {            if( !validateField($(this)) ) {                $(this).addClass("error");                $(this).removeClass("good");            } else {                $(this).removeClass("error");                $(this).addClass("good");            }                }).val("");    });                                // if any ellipsis    $(".autoEllipsis").each(function() {        var parent = $(this);        var moreSel = parent.find(".more");        var more = "&hellip;" + $('<div>').append(moreSel.clone()).remove().html();        moreSel.remove();        parent.autoEllipsis({ellipsis : more, addEllipsisAnyway : true});    });    // if titular daily offer    var titularoffer = $("#dailyoffer");    if(titularoffer.length==1) {        $(".gotoInner").click(function() { location.href = titularoffer.data("href"); });    }                // if weekly offer    if($("#currentoffer").length==1) {        $(".more").click(function(e) {            $(".more").find("span").toggle();            $("#descriptionFull").slideToggle(600);            e.preventDefault();        });    }    // if partners search form    var auto = $(".autocomplete");    if(auto.length>0) {        var accentMap = {            "ą": "a", "Ą": "A",            "č": "c", "Č": "C",            "ę": "e", "Ę": "E",            "ė": "e", "Ė": "E",            "į": "i", "Į": "I",            "š": "s", "Š": "S",            "ų": "u", "Ų": "U",            "ū": "u", "Ū": "U",            "ž": "z", "Ž": "Z"        };        var normalize = function( term ) {            var ret = "";            for ( var i = 0; i < term.length; i++ ) {                ret += accentMap[ term.charAt(i) ] || term.charAt(i);            }            return ret;        };        auto.each(function() {           //var source = $(this).attr("alt");           //console.log(cache);           var self = $(this);           //console.log("autocomplete init on", self);           if(self.hasClass("partners")) {                		self.autocomplete({			source: function( request, response ) {				$.ajax({					url: "http://dailycard.lt/autocomplete.php",					dataType: "jsonp",					data: {                                                type: "JSON",                                                src: "partners",						max: 12,						searchfor: request.term					},					success: function( resp ) {						response( $.map( resp.data, function( item ) {							return {								label: item.label,								value: item.value							}						}));					}				});			},			minLength: 2,			select: function( event, ui ) {				/*console.log( ui.item ?					"Selected: " + ui.item.label :					"Nothing selected, input was " + this.value);*/			}/*,			open: function() {				$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );			},			close: function() {				$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );			}*/		});                          } else {               self.autocomplete({                    source: function( request, response ) {                        var matcher = new RegExp( $.ui.autocomplete.escapeRegex( request.term ), "i" );                        response( $.grep( citycache, function( value ) {                            value = value.label || value.value || value;                            return matcher.test( value ) || matcher.test( normalize( value ) );                        }) );                    }               });           }        });    }                  // if weekly offer buy form    if($("#buyform").length==1) {        var q = $("#quantity");            q.val("1").change(function() {            var val = isNaN($(this).val()) ? 1 : parseInt($(this).val());            var couponsLeft = parseInt($("#totalCoupons").val()) - parseInt($("#totalBought").val());            if(val>couponsLeft) val = couponsLeft;            if(val < 1) { val = 1; }            $(this).val( val );            updateSum();        });        $("#plus").click(function(e) {        	e.preventDefault();            var newval = parseInt(q.val())+1;            var couponsLeft = parseInt($("#totalCoupons").val()) - parseInt($("#totalBought").val());            if(newval<=couponsLeft) q.val(newval);            updateSum();                    });        $("#minus").click(function(e) {        	e.preventDefault();            if(parseInt(q.val()) > 1) {                q.val( parseInt(q.val())-1 );                updateSum();            }        });            $("#agree").change(function() {            if($(this).attr("checked")) $("label[for='agree']").removeClass("error");            $("#agreemsg").hide(300);        });        $("#email").change(function() {            if(!$(this).hasClass("error")) {            	$("#emailmsg").hide(300);            }        })        $("#theform").submit(function(e) {            valid = true;            $(this).find(".error:visible").each(function() { $(this).change(); if($(this).hasClass("error")) valid = false; });            if($("#email").hasClass("shadow") || !$("#email").change().hasClass("good")) {            	trigger("error", "#emailmsg", "Blogai įvestas el. pašto adresas.");                $.scrollTo( $("#email").parent(), 800 );// bad email                e.preventDefault();            } else if($("#bank").val().length==0) {            	alert("Tęskite spausdami ant banko puslapio apačioje.");            	e.preventDefault();            } else if(!$("#agree").attr("checked")) {               $("label[for='agree']").addClass("error");               trigger("error", "#agreemsg", "Privalai sutikti su DailyCard.lt taisyklėmis.");               e.preventDefault();            }        });            }        // if get card form    if($("#getcard").length==1) {        $("#getcard").submit(function(e) {            e.stopImmediatePropagation();            e.preventDefault();            var form = $(this);            valid = true;            if($("#email").change().hasClass("good")) {                form.find("input[type='text']").each(function() {                   if($(this).val()=="" || $(this).hasClass("shadow")) {                       valid = false; $(this).addClass('error');                   }                });                if(!valid) {                    trigger("error", "#getcardWrap", "Privalai užpildyti visus laukelius.");                 }                /*if(valid && $("#agree").attr("checked")==false) {                    valid = false;                    $("label[for='agree']").addClass("error");                    trigger("error", "#getcardWrap", "Privalai sutikti, kad su Tavimi susisiektų DnB NORD banko darbuotojas.");                 }*/                if(valid) {                    var post = {};                    form.find("input[type='text']").each(function() {                        post[$(this).attr("name")] = $(this).val();                    });                    post["subscribe"] = $("#subscribe").attr("checked") ? "1" : "0";                    if(post["subscribe"])                    	$.get(path+"index.php?ajax&city=&regEmail="+$("#email").val());                                        $.post("index.php?ajax&getCard", post, function(response) {                        trigger("success", "#getcardWrap", "Anketa sėkmingai užpildyta! Kelių dienų bėgyje su Tavimi susisieks DnB NORD banko darbuotojas.");                        $("#helper").hide(300);                        $("#getcardWrap").height($("#getcardWrap").height()+"px");                        form.slideUp(800, function() {                                                    });                   });                                   }            } else {               trigger("error", "#getcardWrap", "Blogai įvestas el. pašto adresas.");             }        });                                    }         // general form    if($(".theform").length>0) {                $("#agree").click(function() {            $("label[for='agree']").removeClass("error");        });        $(".required").change(function() {            var field = $(this);            if( validateField(field) ) {                field.removeClass("error");                field.addClass("good");                            } else {                field.addClass("error");                field.removeClass("good");                          }        });    }}function validateCard(callback) {    var field = $("#card");    $.getJSON(path+"index.php?ajax&checkCard="+field.val(), function(response) {        callback(response.success);    });}function validateEmail(email) {    var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;      if( email!=undefined && email!="" && emailPattern.test(email) ) {        return true;    } else {        return false;    }}function validatePhone(number) {    //123456789012345678    //37062697865    //862697865    //console.log(number);    if( number != undefined) number = number.replace(/\s/g, "");    //console.log(number);    var numberPattern = /^(\+3706|86)[0-9]{7}$/;// /^\+?[0-9]{9,11}$/;    if( number!=undefined && number!="" && numberPattern.test(number) ) {        return true;    } else {        return false;    }}function validateField(field) {    var val = field.val();    var pass = true;    if(val=="") pass = false;    if(pass && field.hasClass("email") && !validateEmail(val)) pass = false;    if(pass && field.hasClass("phone") && !validatePhone(val)) pass = false;    if(pass && field.hasClass("code") && $("#"+field.attr("name")).val()==val) pass = false;    return pass;}function updateSum() {    var itemCost = parseFloat($("#itemCost").val());    var quantity = parseInt($("#quantity").val());    var sum = itemCost * quantity;    $("#equals").each(function() {        $(this).html(sum);    });}function toggleBlock(selector) {    var elems = $(selector).find(".toggle");    elems.each(function() {        $(this).toggle();    });}function toggleCities(source) {    var parent = $(source).closest(".cityselector");    var target = parent.find(".nlC");    if(target.is(":hidden")) {        target.show(300);        //src.show("blink", 500);    } else {        target.hide(300);        //src.hide("blink", 500);    }}function pickNlC(initiator, cityid, name) {    newsletterCity=cityid;        var parent = $(initiator).closest(".cityselector");    toggleCities(parent);    parent.find(".nlSC").html(name);}function pickCity(cityid) {    $.cookie('currentCity', cityid, {expires: 365, path: '/'});    location.reload();}function registerNewsletter(initiator) {    var container = $(initiator).closest(".newsletter");    var emailField = container.find(".email");    //var phoneField = container.find(".phone");    if(newsletterCity=="") {        trigger("error", container, "Privalote pasirinkti miestą.");    } else {        var query = path+"index.php?ajax&city="+newsletterCity+"&";        var validEmail = emailField.change().hasClass("good");       // var validPhone = phoneField.change().hasClass("good");        //if(validEmail || validPhone) {        if(validEmail) {            if(validEmail) {                var email = emailField.val();                $.get(query+"regEmail="+email);            }/*            if(validPhone) {                var phone = phoneField.val();                $.get(query+"regPhone="+encodeURI(phone));            }*/            emailField.val("").removeClass("good").removeClass("error").blur();            //phoneField.val("").removeClass("good").removeClass("error").blur();                        var str = "Tavo " +                (validEmail ? "el. pašto adresas" : "") +                //(validEmail && validPhone ? " ir " : "") +                //(validPhone ? "telefono numeris" : "") +                 " sėkmingai užregistruotas" +                //(validEmail && validPhone ? "i" : "as") +                "! Lauk naujienų.";                        trigger("success", container, str);            var popup = container.closest("#nlpopup");            if(popup.length>0) {                setTimeout("$('.nlpopup').hide(300);",3000);            }        } else {            //trigger("error", container, "Blogas el. pašto adresas ir mob. tel. numeris.");            trigger("error", container, "Blogas el. pašto adresas");        }    }}    function trigger(status, selector, text) {    var div = $(selector);    if(!div.hasClass("message")) div = div.find(".message");    if(div.length>0) {        //console.log(div);        div.removeClass(status=="error" ? "success" : "error").addClass(status);        var msgtext = div.find(".msgtext");        msgtext.html(text);        if(div.is(":hidden")) div.slideDown(300);                div.find(".msgicon").position({            my:"right center",            at:"left center",            of:msgtext,            offset:"-5 0"        });    }}function faq(child) {    var li = $(child).parent();    var ul = li.parent();    var expand = true;    var answer = li.find(".answer");    if(li.hasClass("selected")) {        li.removeClass("selected");        answer.hide("blind", 500);    } else {        var prev = ul.find("li.selected");        prev.removeClass("selected").find(".answer").hide("blind", 500);        answer.show("blind", 500);        li.addClass("selected");                /*, function() {        	li.addClass("selected");        	li.prevAll(":last").before(li);        	//.show(); list.prepend(li); li.hide();        	li.find(".answer").show();        	li.show("blind", 500);        });*/                /*, function() {            if($.browser.msie) {                $(this).find("ol,ul").css("display", "block");                //alert(matched.length);            }        });                                                      */    }    }function inquiry(element) {	var query = element.val();	var partnerfaqID = element.data("id");	if(query=="") {		alert("Negalite siųsti tuščios užklausos.");	} else {		$.post(path+"index.php?ajax&sendInquiry", { "faqID":partnerfaqID, "query":query }, function() {			element.val("");			alert("Užklausa išsiųsta, laukite kol su jumis susisieks Daily Card darbuotojai!");//+"\npartnerfaqID "+partnerfaqID+"\nquery "+query		});	}	}function showTellFriend(offerid) {    $.get(path+"index.php?ajax&showTellFriend", function (response) {        var init_func = function() {            $("#tellFriend").submit(function(e) {                e.preventDefault();                var form = $(this);                var pass = true;                var post = {};                form.find(".field").each(function() {                    if(!validateField($(this))) {                        pass = false;                    } else {                    }                    post[$(this).attr("name")] = $(this).val();                });                if(pass) {                    post["offerid"] = offerid;                    $.post(path+"index.php?ajax&tellFriend", post, function(r) {                          form.find(".wrapper").slideUp("fast");                          form.find(".success").slideDown("fast");                          setTimeout("closeDialog();", 2500);                    });                   }            });        };        showDialog(response, {width: 'auto'}, init_func, "Pranešk draugui!");    });    }function blinkBad(jqueryElem) {	$(jqueryElem).each(function() {		var self = $(this);		var borderColor = self.css("borderTopColor");		self.animate({ borderColor:"#ff0000" }, 1000, function() {			self.animate({ borderColor:borderColor }, 500);		});	});}function showLottery() {	//var lottery = ;	//var content = lottery.clone();	//content.attr("id", "").removeClass("hidden");	var initFunction = function() {		init_defaulttext();		var form = $("#dialog .lotteryform");		form.submit(function(e) {			e.preventDefault();			e.stopPropagation();			var self = $(this);			var nonvalid = Array();			var post = {};			self.find("input[type='text']").each(function() {				if($(this).hasClass("shadow") || $(this).val().length <= 0) {					nonvalid.push(this);				} else {					if($(this).attr("name")!=undefined) {						post[$(this).attr("name")] = $(this).val();					}				}			});			if(nonvalid.length > 0) {				alert("Privalote užpildyti visus laukus!");				blinkBad(nonvalid);				return;			}						var email = self.find(".email");			if(!validateEmail(email.val())) {				alert("Neteisingai įvestas el. pašto adresas!");				blinkBad(email);				return;			}			var postUrl = path+"index.php?ajax&lottery&ref=site";			self.find("input:checked").each(function() {				postUrl += "&" + $(this).attr("name") +"="+ $(this).val();			});			$.post(postUrl, post, function(response) {								alert("Sveikiname, tu dalyvauji konkurse!\nLaimėtoją skelbsime "+self.data("until") + ".");				closeDialog();			});		});		form.find(".dropdown").bind("click", function(e) {			var self = $(this);			var box = self.next();						if(box.is(":visible")) {				form.find(".thebox:visible").not(box).slideUp(100);			} else {				box.show();				box.position({					my:"center top",					at:"center bottom",					of:self				});				box.hide();			}			box.slideToggle(300);		});		form.find(".thebox .toggle").click(function(e) {			e.preventDefault();			$(this).closest(".thebox").slideUp(300);		});		form.find("input[type='checkbox']").change(function() {			var selector = $(this).attr("class");			var names = new Array();			form.find("."+selector).each(function() {				if($(this).is(":checked")) {					names.push($(this).attr("title"));				}			});			var field = $(this).closest(".thebox").prev();			var val = names.join(", ");			if(val.length>0) {				field.removeClass("shadow").val(val);			} else {				field.addClass("shadow").val("");			}		});	}; 	showDialog($("#lottery").html(), {}, initFunction);}var clock = {    container: null,    clocks: {},	minutes: null,	hours: null,	days: null,	timer: null};clock.updateTime = function() {	var c = this;    var now=new Date();    var parsed=Date.parse(now);    var currentsecond = now.getSeconds();    this.container.each(function() {    	var id = $(this).attr("id");    	var curr = c.clocks[id];    	if(currentsecond != curr.prevsecond) {    		curr.prevsecond = currentsecond;    		var timeleft = curr.countdownto - parsed + curr.offset;            var d = Math.floor(timeleft/c.days);            timeleft -= d*c.days;            var h = Math.floor(timeleft/c.hours);            timeleft -= h*c.hours;            var m = Math.floor(timeleft/c.minutes);            timeleft -= m*c.minutes;            var s = Math.floor(timeleft/1000);            c.set(curr.span.days, d, false);            c.set(curr.span.hours, h);            c.set(curr.span.minutes, m);            c.set(curr.span.seconds, s);    	}    });                        this.timer=setTimeout("clock.updateTime()",250);};clock.set = function(span, value, pad) {    var str = '' + value;    if((pad==undefined||pad==true)&&str.length==1)        str = '0' + str;    span.html(str);}clock.init = function(selector) {	var c = this;	this.minutes=1000*60;	this.hours=this.minutes*60;	this.days=this.hours*24;	    this.container = $(selector);    this.container.each(function() {    	var curr = $(this);    	var id = curr.attr("id");    	var countfrom = parseInt(curr.find(".countdownfrom").val())*1000;    	c.clocks[id] = {    		countdownfrom	: countfrom,    		countdownto		: parseInt(curr.find(".countdownto").val())*1000,    		offset			: Date.parse(new Date()) - countfrom,    		prevsecond		: -1,    		span			: {    			days: curr.find(".days"),    			hours: curr.find(".hours"),    			minutes: curr.find(".minutes"),    			seconds: curr.find(".seconds")    		}    	};    });    this.updateTime();};var init = false;$(document).ready(function() {            if(!init) init = true;    else return;    init_site();    //init_checkboxes();        init_newtemplate();        init_defaulttext();});function init_site() {	var exMore = $(".expand.more");		$(".expand").click(function(e) {		e.preventDefault();		var offer = $(this).closest(".offer,.parent");		var innerExMore = offer.find(".expand.more");		var toExpand = offer.find(".expanded");		if(!toExpand.is(":visible")) {			$(this).closest(".content").find(".expanded:visible").slideUp(300);			toExpand.slideDown(300);			exMore.show();			innerExMore.hide(300);			$(".full").removeClass("full");			offer.addClass("full");		} else {			exMore.show(300);			toExpand.slideUp(300,function() {				offer.removeClass("full");			});		}	});		$("a[rel=photos]").fancybox({		'transitionIn'		: 'none',		'transitionOut'		: 'none',		'titlePosition' 	: 'over',		'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) {			return '<span id="fancybox-title-over">Nuotrauka ' + (currentIndex + 1) + ' iš ' + currentArray.length + (title.length ? ' &nbsp; ' + title : '') + '</span>';		}	});	/*exMore.each(function() {		$(this).appendTo( $(this).prev() );	});	//.appendTo( $(".basic .description > :last-child") );	 */	}
