// Common JavaScript code across your application goes here.
//
jQuery.preloadImages = function(){
    jQuery.each (arguments,function (e){
        jQuery ('<img src="' + this + '" />');
    });
}

function showgallery(){
    $.getJSON("/imgs.json", function(datum){  

        $('.left').html("<div class='content'><div class='closebtn'></div><img src='/images/newsprint.png'><div class='contentdis'><h1>Gallery</h1><form class='remote' action='/images/upload' method='post' enctype='multipart/form-data'><p>title:<input type='text' name='title'></p><p>file:<input type='file' name='file' size='20'/></p><p>description</p><textarea id='editor' name='description'></textarea><input type='submit' value='upload'/></form></div></div>");
        for (var i = 0; i < datum.length; i += 1) {
            $('.contentdis').append("<a href='/uploads/gallery/orig_"+datum[i].filename+"' title='"+datum[i].title+"' class='thickbox' rel='gallery'><img src='/uploads/gallery/thumb_"+datum[i].filename+"' alt='sample "+i+"'></a>");
        }

        //$('form.remote').submitWithAjax();

})
}



$('#prizes').css('background','none');
function prizesOn(){

    $('#prizes').hover(
    function(){
      $('.psychicwindow').show();
    
        psychicsign = true;   
    },
    function(){
        $('.psychicwindow').hide();
        psychicsign = false;
    }
    )}
    

function prizesOff(){
    $('#prizes').bind('mouseenter mouseleave',  function(e){
        $('.psychicwindow').show();
        psychicsign = true;

        return false;
    });


}


       
        
                
        
		function updateTips(t) {
            $("#validateTips").text(t).addClass('ui-state-error');
		}

		function checkLength(o,n,min,max) {

			if ( o.val().length > max || o.val().length < min ) {
				o.addClass('ui-state-error');
				updateTips("Length of " + n + " must be between "+min+" and "+max+".");
				return false;
			} else {
				return true;
			}

		}
        
        function checkIssueDups(o,n){
            for(issue in issues){
                if(o == issues[issue].production){
                    o.addClass('ui-state-error');

                    updateTips(n);
                    return false;
                }
            }
        }
		function checkRegexp(o,regexp,n) {

			if ( !( regexp.test( o.val() ) ) ) {
				o.addClass('ui-state-error');
				updateTips(n);
				return false;
			} else {
				return true;
			}

		}

      	function timedCount(){
            if(typeof count != "undefined" && count < 670) {
                count++;
            }else{
                count = 0;
            }
            if(count % 22 == 0){
                 $('.Csign').toggle(); 
            
            }
            if(count % 3 == 0){
                $('.Csign').show()
                if(typeof psychicsign !== "undefined" && psychicsign == true){
                    $('.psychicsign').toggle();
                }
        
            }
    
            t=setTimeout("timedCount()", 100)    
        }

        showarticle = function(issuenum){
            $(".showissue[rel='"+selectedissue+"']").css('background','#FBEFC5');
                        selectedissue = issuenum;
                        
                        $(this).css('background','#FCF5DE');
                        $('.issueinfoandpurchase').html("<div class='issueinfoandpurchasestats'>"+issues[selectedissue].price+"  "+issues[selectedissue].publish.toString('MMMM  yyyy')+"</div>");
                        $('.issueinfoandpurchase').append("<form target='paypal' action='https://www.paypal.com/cgi-bin/webscr' method='post'><input type='hidden' name='cmd' value='_s-xclick'><input type='hidden' name='hosted_button_id' value='5002303'><input type='image' src='https://www.paypal.com/en_US/i/btn/btn_cart_LG.gif' border='0' name='submit' alt='PayPal - The safer, easier way to pay online!'><img alt='' border='0' src='https://www.paypal.com/en_US/i/scr/pixel.gif' width='1' height='1'></form>");
                        $.getJSON("/articles/"+articleids[issues[$(this).attr('rel')].article]+".json",function(datum){
                        if(datum["title"] != ""){
                             $('#issuearticletitle').html(datum["title"]);
                             $('#issuearticlebody').html(datum["body"]);

                            if( auth && admin){

                                 $('#writebtn-'+$(this).attr('rel')).bind('click',function(e){
                                     window.location.href="/articles/"+articleids[issues[$(this).attr('rel')].article]+"/edit";
                                 }).show();
                            }
                    }
                })

        
        }

         jQuery.fn.submitIssue = function(){

            this.submit(function(e){

            
            e.preventDefault();
         /*   var issueno = $("#issue_production");
			var issue_quantity = $("#issue_quantity");
            var issue_published = $("#issue_published");
			var issue_price = $("issue_price");
            var tips = $("#validateTips");
			var allFields = $([]).add(issueno).add(issue_quantity).add(issue_published).add(issue_price);
			var bValid = true;
            tips.removeClass('ui-state-error'); 
            allFields.removeClass('ui-state-error'); 
            //bValid = bValid && checkRegexp(issue_price,/^\d+(?:\.\d{0,2})?$/,"format for US currency");
            bValid = bValid && checkRegexp(issue_published,/^([0]?[1-9]|[1][0-2])[./-]([0]?[1-9]|[1|2][0-9]|[3][0|1])[./-]([0-9]{4}|[0-9]{2})$/,"mm/dd/yyyy or m/d/yy");
            bValid = bValid && checkIssueDups(issueno,'there is an issue with this production code');
            if(bValid){
            //    alert('is being handled'); 
           */     
                //check validation 
                
                //
                //
                //e.stopPropagation();
                dateconv = Date.parse($('.addremoteissue #issue_published').val()).toString('dd/MM/yy');
                $('.addremoteissue #issue_published').val(dateconv);
                $.post(this.action + '.json', $(this).serialize(), function(data){
                    data.publish = Date.parse(data.publish);
                    issues[data.id] = data; 
                    articleids[data.article] = data.articleid;
                    $('.issuelist').prepend("<li class='showissue' rel='"+data.id+"'>"+data.production+" "+data.title+"</li>");
                    selectedissue = data.id;

                    $(".showissue").css('background','#FBEFC5');

                    
                    $(".showissue[rel='"+selectedissue+"']").css('background','#FCF5DE');
                    $('.issueinfoandpurchase').html(issues[selectedissue].price+"<span> purchase </span>"+issues[selectedissue].publish.toString('MMMM  yyyy'));
                     $('.issueinfoandpurchase').html("<span>"+issues[selectedissue].price+"  "+issues[selectedissue].publish.toString('MMMM  yyyy')+"</span>");
                        $('.issueinfoandpurchase').append("<form target='paypal' action='https://www.paypal.com/cgi-bin/webscr' method='post'><input type='hidden' name='cmd' value='_s-xclick'><input type='hidden' name='hosted_button_id' value='5002303'><input type='image' src='https://www.paypal.com/en_US/i/btn/btn_cart_LG.gif' border='0' name='submit' alt='PayPal - The safer, easier way to pay online!'><img alt='' border='0' src='https://www.paypal.com/en_US/i/scr/pixel.gif' width='1' height='1'></form>");

                    $.getJSON("/articles/"+issues[selectedissue].articleid+".json",function(datum){

                       $('#issuearticletitle').html(datum["title"]);
                             $('#issuearticlebody').html(datum["body"]);

                              $('.closebtn').bind('click',function(e){
                                     $('.left').empty();
                                     $('#issues').css('background','none');
                                 }).show();
                            if( auth && admin){

                                 $('.writebtn').bind('click',function(ev){
                                     ev.preventDefault();
                                    ev.stopPropagation();

                                      $('.contentdis').html("<form class='addremoteissue' action='/issues/"+issues[selectedissue].id+"' method='post'><p id='validateTips'>All form fields are required.</p><p>issue title :  <input type='text' id='issue_title' name='issue[title]' class='text' value='"+issues[selectedissue].title+"'/>  </p><p>issue number : <input type='text' id='issue_production' name='issue[production]' class='issuenofield text' value='"+issues[selectedissue].production+"'/> published : <input type='text' id='issue_published' name='issue[published]' class='dateselect text' value='"+issues[selectedissue].publish.toString('MMMM yyyy')+"'/></p><p> qty :<input type='text' id='issue_quantity' name='issue[quantity]' class='integerfield text' value='"+issues[selectedissue].quantity+"'/> price : &#36;<input type='text' id='issue_price' name='issue[price]' class='currencyfield text' value='"+issues[selectedissue].price+"'/></p><p><input type='submit' id='submit' name='submit' value='update'/></p></form><p id='issuearticlebody'></p>");     

                                 }).show();
                            }
 
                    });

                   
               }, "json");

                //}else{
                //return false;
                //}
            }); 
        };



        jQuery.fn.submitWithAjax = function() {
            this.submit(function() {
                $.post(this.action + '.json', $(this).serialize(), function(data){}, "json");
                return false;
            })
            return this;
        };


