(function($){
    $.unserialise = function(Data){
        var Data = Data.replace("?",'&');
        Data = Data.split("&");
        var Serialised = new Array();
        $.each(Data, function(){
            var Properties = this.split("=");
            Serialised[Properties[0]] = Properties[1];
        });
        return Serialised;
    };
})(jQuery);

$(document).ready(function(){

			 
    var  baseUrl = $('base').attr('href');
    var sandsDropDownMenu = {
				
        navLinkProp : '.ulTopNavigator > li',
        container : null ,
        submenuName :'.submenu',
        run:function(){
            $(sandsDropDownMenu.navLinkProp).hover(function(i){
                if(navigator.appName !='Microsoft Internet Explorer')
                    $(sandsDropDownMenu.navLinkProp).css({
                        'z-index':'10'
                    });
                $('ul',this).slideDown('slow');
            },function(){
                $('ul',this).slideUp('slow');
            });
        },
        init: function(container){
            sandsDropDownMenu.container = container;
            sandsDropDownMenu.run();
        }
			
    };

			 
	 
    $('.HeadTitleProduct > a').click(function(e){
        e.preventDefault();
        $('.HeadTitleProduct > a').css({
            background: null
        });
        $(this).css({
            background: 'url("img/accordeon-head-hover.gif") 0 0 no-repeat'
        });
        // $(this).next().slideToggle('fast');
		 		 
				 
        //mini accordeon :P
        if ($(this).next().is(":hidden") ) {
            $('.HeadTitleProduct > a').next().slideUp();
            $(this).next().slideDown();
        }
					
					
	 				 
    });
	
	
	  
		
		
    $('.submenuProduct a[class!=noLoadContent]').click(function(e){
        //e.preventDefault();
        var anchor =  $(this).attr('href').split('#');
        $('.submenuProduct a').css('background-color' , null);
        $(this).css({
            'background-color': '#51DE8B' ,
            'color' : '#000',
            'font-weight' : 'normal'
        });
        var parentTag = $(this).parent().parent().parent().children('a');
			 
        $('.HeadTitleProduct > a').css({
            background: null
        });
        $(parentTag).css({
            background: 'url("img/accordeon-head-hover.gif") 0 0 no-repeat'
        }).hide().fadeIn('slow');
        $('#left').show().html('<img src="img/loader.gif" align="center">');
        loadContent(anchor[1]);
    });
		
		
		
		
    $('.imageNav#next').live('click',function(e){
        var theid = location.hash.replace(/^#/, "");
        theid = parseInt(theid) + 1;
    //alert( theid );
    });
		
		
    $('.imageNav#prev').live('click',function(e){
        var theid = location.hash.replace(/^#/, "");
        theid = parseInt(theid) - 1;
    //alert( theid );
    });
	
		
    $('.imageNav#next').live('mouseover',function(e){
        $(this).css({
            'background' : 'url("img/nextPrev.gif") 8px -50px no-repeat' ,
            'cursor' : 'pointer'
        })
    }).live('mouseout',function(e){
        $(this).css({
            'background' : 'url("img/nextPrev.gif") 8px 0px no-repeat' ,
            'cursor' : 'pointer'
        });
    });
		
		
    $('.imageNav#prev').live('mouseover',function(e){
        $(this).css({
            'background' : 'url("img/nextPrev.gif") -60px -50px no-repeat' ,
            'cursor' : 'pointer'
        })
    }).live('mouseout',function(e){
        $(this).css({
            'background' : 'url("img/nextPrev.gif") -60px 0px no-repeat' ,
            'cursor' : 'pointer'
        });
    });
		
		    	
    var loadContent = function(id) {
 
        if(!id || id == '') return false;
        $.post(baseUrl + "detail_product",{
            category:id,
            ProductID:id,
            principle:0,
            isAjax:true
        },function(data) {
            $('#left').show().html(data);
						 
        });
    };

	
    if (location.hash) {
        var theid = location.hash.replace(/^#/, "");
        $('#left').hide();
        loadContent(theid);
    }

    sandsDropDownMenu.init($('.mainContent'));
 	
    //simple jquery by sandy
    //mode random

    var i = Math.floor(Math.random() * 11 );
    var imageRand = function (){
        i +=1;
        y = i % 4;
        $('.bannerContainer').animate({
            opacity: 1.0
        },3000).css({
            'background' : 'url("img/banner'+ y  +'.gif") 0 0  no-repeat'
        }).animate({
            opacity: 0.0
        },5000);
        setTimeout(imageRand, 8000);
    }
    setTimeout(imageRand, 10);
					
	 
    $("#formInput").submit(function(){
							
        var news_title = $('#news_title').val();
        if (news_title == '') {
            $('#notification').html("News Title cannot be blank!").css('background-color','red');
            $('#formInput > table tr').eq(0).addClass('BgNotify');
            return false;
        }
        $.ajax({
            type: 'POST',
            url: $(this).attr('action'),
            data: $(this).serialize(),
            //success: getDatas
            success:function(){
                document.location.href = 'admin/news';
            }
        })
						
        $("input[type=text],input[type=hidden],textarea").val('');
        $("#formNews").slideUp();
        $("#mask").fadeOut();
        return false;
    });
 
    $("#addNews").click(function(e){
        $("input[id='insert']").val('insert');
        showForm();
		
    });
		
    $("#deleteNews").live('click',function(e){
        $.post("admin/newsdelete", {
            news_id: $(this).attr('title')
            }, getDatas );
    });
		
		
		
    $("#mask").click(function(e){
				
        $("input[id!=insert]").val('');
        $("textarea").html('');
        $("#formNews").slideUp();
        $(this).fadeOut();
    });
		
    $("#editNews").live('click',function(e){
			
        $("input[id='insert']").val('update');
        var news_id = $(this).attr('title');
        var fields = $("#formInput").serializeArray();
        $.getJSON("admin/getnews/" + news_id, function(datas){
            $.each(datas[0],function(d,ditem){
                $('textarea[name=' + d + ']').html(ditem+'&nbsp;');
                $('input[name=' + d + ']').val(ditem);
			
            });
						
        });
				
        showForm();
			
    });
		
		
			
    function showForm(){
        $('#notification').html('');
        var w = $(document).width();
        var h = $(document).height();
        var boxposx = w / 2;
        var formNewsw = $("#formNews").width() / 2;
        var pos = boxposx - formNewsw;
        $("#mask").css({
            'width': w ,
            'height' : h
        }).show().animate({
            opacity:0.9
        });
        $("#formNews").hide();
        $("#formNews").css({
            'top' : '0' ,
            'left' : pos + 'px'
        }).slideDown('fast');
    }
		
    $('.submenu#chooseLang > li a').live('click',function(){
        var id = $(this).attr('id');
        //alert(id);
        $('#setlang').val(id);
        $('#frmlang').submit();
    });
    $('#news_detail').tinymce({
		 	
			
        // Location of TinyMCE script
        script_url : baseUrl + 'js/tiny_mce/tiny_mce.js',
			 
        // General options
        theme : "advanced",
        plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,advlist",

        // Theme options
        theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
        theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,|,forecolor,backcolor",
        theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
        theme_advanced_buttons4 : "emotions,insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak,preview",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_statusbar_location : "bottom",
        theme_advanced_resizing : true,
        urlconvertor_callback:function(strUrl, node, on_save){
            strUrl=strUrl.replace("../","");
            return strUrl;
        }
  	 
    });
		
	 
			
    var getDatas = function(){
        var content = '';
        $.getJSON("admin/getnews", function(data){
										
            $.each(data, function(i, item){
                content += "<tr>";
                content += "<td>" +  item.news_id+ "</td>";
                content += "<td>" +  item.news_title + "</td>";
                content += "<td>" +  item.news_short_description + "</td>";
                content += "<td><a id=\"editNews\" title="+  item.news_id + ">Edit</a> |";
                content += " <a id=\"deleteNews\" title="+  item.news_id + ">Delete</a></td>";
                content += "</tr>";
            });
														
            $("#datas > tbody").html(content);
        });
							
    }
						
 				
    getDatas();
					
					
								
				
});
