var i=1;
var view='';
var obj;
function showProcess(header){
            if(!header){
              header='Processing Edit, Please Wait...';
            }
            $("#processing").show();
            $("#process_header").html(header);
            $.facebox($("#processing"));
            $(document).bind('close.facebox', function() {
                setTimeout("$('#upload_frame').before($('#processing'))",500);
                setTimeout("$('#processing').css({display:'none'})",1000);
            });
}
function reEditLinks(){
                $('.item').find('.description').each(function(){
                       var reg1=/\[link\=(.|\s)*/;
                       var reg2=/\[link\=.*\](\w|\s)*\[\/link\]/g;
                       if($(this).html().match(reg1)){
                                 var linkcode=new Array();
                                 linkcode=$(this).html().match(reg2);
                             for(var i=0;i<linkcode.length;i++){
                                 var regexp = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
                                 var href=linkcode[i].match(regexp).toString().substr(0,$(this).html().match(regexp).toString().indexOf(']')).replace(/\](.|\s)*\[\/link\]/,'');
                                 var getText=linkcode[i].toString().match(/\](.|\s)*\[/)[0];
                                 getText=getText.replace(/\]/,'').replace(/\[/,'');
                                 var hrefcode='<a href="'+href+'" target="_blank">'+getText+'</a>';
                                 $(this).html($(this).html().replace(linkcode[i],hrefcode));
                             }
                       }
                });
}
function doEdit(obj){
            $("#editbox").show();
            var item=$(obj).parent(0).parent(0).attr('id');
            var $getDiv=$(obj).parent(0);
            $('#ttl').val($getDiv.find('h3').html());
            $('#price').val($getDiv.find('.price').html());
            if($getDiv.find('.description').find('a').length > 0){
                $getDiv.find('.description').find('a').each(function(){
                    var href=$(this).attr('href');
                    var txt=$(this).html();
                    var linkcode="[link="+href+"]"+txt+"[/link]";
                    $(this).replaceWith(linkcode);
                });
            }
            var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi; 
            var str=$getDiv
                    .find('.description')
                    .html()
                    .replace(regexp,'')
                    .replace($('#ttl').val(),"")
                    .replace($('#price').val(),"");
            $('#desc').val($.trim(str));
            var str1=$('#desc').val().split('\n|\r');
            var newdesc='';
            for(var i=0;i<str1.length;i++){
                str1[i]=str1[i].replace(/\n|\r/,'');
                newdesc+=$.trim(str1[i])+'\n\n';
            }
            $('#desc').val($.trim(newdesc));
            $.facebox($('#editbox'));
            $(document).bind('close.facebox', function() {
                reEditLinks();
                obj=null;
                setTimeout("$('#loginbox').before($('#editbox'))",500);
                setTimeout("$('#editbox').css({display:'none'})",1000);
            });
            $('#EditItem').click(function(){
                doEditPost($getDiv,item);
            });
}
function doEditPost(obj){
            var newLines = /(\r|\n)/g;
            var newTitle=$('#ttl').val();
            var newDesc=$('#desc').val().replace(newLines,'<br>\n');
            var newPrice=$('#price').val();
            if(newTitle == ''){
               alert('Please Enter a Title...');
               return false;
            }
            if(newDesc == ''){
               alert('Please Enter a Description...');
               return false;
            }
            $(obj).html(
'  <div class="_image">\n'+$(obj).find('._image').html()+
'  </div>\n'+
'  <div class="description">\n  <h3>'+newTitle+'</h3>\n'+
'  <p>'+newDesc+'</p>\n'+
'  <p class="price">'+newPrice+'</p>\n'+
'  <br clear="all">\n'+
'  </div>\n'
            );
            reEditLinks(); 
            $(document).trigger('close.facebox');

            view=$(obj).parent(0).attr('id');
            setTimeout('showProcess()',500);
            obj=null;
            editListings(view+'_show');
}
function doCommentPost(obj){

            var cmnt='';
            $(obj).find('.edit').nextAll('br').remove();
            $(obj).find('.edit').remove();            
            var newLines = /(\r\n|\n\n|\n\r|\r|\n)/g;
            cmnt=$('#cmmnt').val().replace(newLines,'<br>');
            if($(obj).find('.comment').is('p')){
                 $(obj).find('.comment').remove();
                 $('<p class="comment">'+cmnt+'</p>\n').insertAfter($(obj).find('.price'));
            }
            else{
                 $('<p class="comment">'+cmnt+'</p>\n').insertAfter($(obj).find('.price'));
            } 
            $(document).trigger('close.facebox');

            view=$(obj).parent(0).attr('id');
            setTimeout('showProcess()',500);
            obj=null;
            editListings(view+'_show');
}
function doComment(obj){
            $("#commentbox").show();
            $getDiv=$(obj).parent(0);
            if($getDiv.find('.comment').is('p')){
                  $('#cmmnt').val($getDiv.find('.comment').html());
            }
            $.facebox($("#commentbox"));
            $(document).bind('close.facebox', function() {                
                obj=null;
                setTimeout("$('#loginbox').before($('#commentbox'))",500);
                setTimeout("$('#commentbox').css({display:'none'})",1000);
            });
            $('#EditItem2').click(function(){
                doCommentPost($getDiv);
            });
}
function addItem(){

            $("#addbox").show();
            $.facebox($("#addbox"));
            $(document).bind('close.facebox', function() {
                $('#image_preview').html('<div id="fileprogress" style="font-size:2em;font-weight: bold;width:340px;height:300px;line-height:300px;text-align:center;"> </div>').css({height:'300px'});
                $('#item_text').css({display:'none'});
                $('#image_upload').css({display:'block'});                
                obj=null;
                setTimeout("$('#editbox').before($('#addbox'))",500);
                setTimeout("$('#addbox').css({display:'none'})",1000);
            });
}
function addItemPost(cat){
            if(cat=='other' && $('#other').css('display')=='none'){
               $('#other').css({display:'block'});
            }
            view=cat;
            cat='#'+cat;
            var newLines = /(\r|\n)/g;
            var newTitle=$('#addttl').val();
            var newDesc=$('#adddesc').val().replace(newLines,'<br>\n');
            var newPrice=$('#addprice').val();
            if(newTitle == ''){
               alert('Please Enter a Title...');
               return false;
            }
            if(newDesc == ''){
               alert('Please Enter a Description...');
               return false;
            }
            newPrice=(!isNaN(newPrice) && newPrice.indexOf('$') < 0) ? '$'+newPrice : newPrice;
            var newImage=$('#image_preview').html();
            var newItem=
'<div class="item">\n'+
'  <div class="_image">\n'+newImage+
'  </div>\n'+
'  <div class="description">\n  <h3>'+newTitle+'</h3>\n'+
'  <p>'+newDesc+'</p>\n'+
'  <p class="price">'+newPrice+'</p>\n'+
'  <br clear="all">\n'+
'  </div>\n'+
'</div>\n';
            $(document).trigger('close.facebox');

            var newElem=$(newItem);
            $(newElem).insertAfter($(cat).children('.heading'));
            $(newElem).css({borderTop: 'solid 1px #000080',borderBottom: 'solid 1px #000080'});
            reEditLinks();
            setTimeout('showProcess(\'Adding Item, Please wait...\')',500);
            newElem=null;
            editListings(view+'_show');
}
function doDelete(obj){
     var areyousure = confirm('Are you sure you wish to Delete this Item?\n\nClick "OK" to Delete, "Cancel" to cancel deletion.');
     if(areyousure){

            view=$(obj).parent(0).attr('id');
            var delimage=$(obj).find('._image img').attr('src');
            $.post('/delete.php', {image : delimage});
            $(obj).remove();
            if($('#other').children().length == 1){
                $('#other').css({display:'none'});
            }
            setTimeout('showProcess(\'Deleting Item, Please Wait...\')',500);
            obj=null;
            editListings(view+'_show');
     }
     else{            
            obj=null;
            $(document).trigger('close.facebox');
     }
}
function doSold(obj){
     $(obj).insertAfter($('#sold').children('.heading'));
     $(obj).find('.edit').remove();
     $(obj).find('.price').remove();
     $('<p class="price">SOLD</p>\n').insertAfter($(obj).find('.description p:last'));
     if($('#other').children().length == 1){
         $('#other').css({display:'none'});
     }
            $("#processing").show();
            $("#process_header").html('Setting Item as Sold, Please Wait...');
            $.facebox($("#processing"));
            obj=null;
            editListings('sold_show');
}
function doLogin(){
     $('#loginbox').fadeIn('slow');
     $.facebox($('#loginbox'));
}
function addEditButton(obj){
      if($(obj).parent(0).attr('id') != 'sold'){
          if(!$(obj).find('.edit').is('div')){
              $(obj).append('<div class="edit" style="float:right;background:#555555;border:solid 1px #000000;text-align:center;color:#FFFFFF;font-weight:bold;width:240px;"><p id="soldbutton" style="margin:2px;float:right;border-left:solid 1px #FFFFFF;cursor:pointer;width:75px;" onclick="doSold($(this).parent(0).parent(0));">Sold</p><p style="margin:2px;cursor:pointer;float:right;width:75px;" onclick="doEdit($(this).parent(0));">Edit</p><p style="margin:2px;float:right;border-right:solid 1px #FFFFFF;cursor:pointer;width:75px;" onclick="doDelete($(this).parent(0).parent(0));">Delete</p></div><br clear="all"><br clear="all">');
          }
      }
      else{
          if(!$(obj).find('.edit').is('div')){
              $(obj).append('<div class="edit" style="float:right;background:#555555;border:solid 1px #000000;text-align:center;color:#FFFFFF;font-weight:bold;width:175px;"><p style="margin:2px;float:right;cursor:pointer;width:75px;border-left:solid 1px #FFFFFF;" onclick="doDelete($(this).parent(0).parent(0));">Delete</p><p style="margin:2px;cursor:pointer;float:right;width:90px;" onclick="doComment($(this).parent(0));">Comment</p></div><br clear="all"><br clear="all">');
          }
     }
}
function editListings(show){
     if(show){
        show='&view='+show;
     }
     else{
        show='';
     }
     $('.item').each(function(){
              $(this).css({border: '0px'});
              $(this).find('.edit').nextAll('br').remove();
              $(this).find('.edit').remove();
     });
     $.post('/edit.php', {newhtml : escape($('#editable').html())}, function(data){
         if(data=='success'){
            top.location.href='horses-for-sale.php?edit=success'+show;
         }
         else{
            top.location.href='horses-for-sale.php?edit=failed'+show;
         }
     });
}
