// General Functions
function validateEmail(elementValue){
    var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    return emailPattern.test(elementValue);
}




function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

function get(v){
    return decodeURI(getUrlVars()[v])
}

//check if the jQuery Object exist in DOM
function exist(jQ)
{
    return (jQ.length>0);
}

//Global Variable
var lock= false;

// Document Ready 
$(document).ready(function(){
    $('.follow-us #email')
    .focus(
        function()
        {
            if($(this).val()=='Join our Newsletter')
            {
                $(this).val('');
            }
        })
    .blur(
        function()
        {
            if($(this).val()=='')
            {
                $(this).val('Join our Newsletter');
            }
        })
		
//Tiny Scroll Bar
		
})

$(window).load(function(){
	
    })
//SITE FUNCTIONS

//set the current menu item to active
//@id	int : the index of the element 
function setActiveMenu(id)
{
    $('.top-menu td').removeClass('active')
    var $active = $('.top-menu td:eq('+id+')')
    $active.addClass('active')
	
    //store the active menu in cache, to retreive it later
    if(exist($('head input#__ACTIVE')))
    {
        $('head input#__ACTIVE').val(id)
    }
    else
    {
        $('head').append('<input type="hidden" id="__ACTIVE" value="'+id+'" />')
    }
	
}

function showAboutUs(id)
{
    $('.page-content').html($('#aboutus').html()).fadeIn(200,function(){
        $('#scrollbar1').tinyscrollbar();
    })
    setActiveMenu($(id).index())
    $('.products:visible').hide();
//$('.products:visible').hide("drop", { direction: "left" }, 1000);
}

function showContactUs(id)
{
    $('.page-content').html($('#contactus').html()).fadeIn()
    setActiveMenu($(id).index())
    $('.products:visible').hide();
//$('.products:visible').hide("drop", { direction: "right" }, 1000);

}

function showCustomerCare(id)
{
    $('.page-content').html($('#customercare').html()).fadeIn()
    setActiveMenu($(id).index())
    $('.page-content .customercare #fname').focus();
    $('.products:visible').hide();
//$('.products:visible').hide("drop", { direction: "down" }, 1000);
}

//get the `Press Releases` from the database via ajax
//@id	int:the id of the menu item (used to set it to active)
//@start optional int: the starting value used for paging,default :0

function showPressReleases(id,start)
{
    start = typeof(start) != 'undefined' ? start: 0;
    var index;
	
    //Retreive the index of the menu item from cache if the passed id is NULL
    index=id==null?$('head input#__ACTIVE').val():$(id).index()
	
    $.ajax({
        url:'admin/main.php?c=press&start='+start,
        success:function(r){
            $('.page-content').html(r).fadeIn()
            setActiveMenu(index)
            $('.products:visible').hide();
        //$('.products:visible').hide("drop", { direction: "right" }, 1000);
		
        }
    })
	
	
}

function showDesignTips(id)
{
    $('.page-content').html($('#design').html()).fadeIn()
    setActiveMenu($(id).index())
    $('.products:visible').hide();
//$('.products:visible').hide("drop", { direction: "down" }, 1000);
}

function showHome()
{
    $('.page-content').empty().fadeOut()
    setActiveMenu(0)
}

$(document).bind('click', function(e) {
    var $clicked = $(e.target);
    //                if (!$clicked.parents().hasClass("page-content") && !$clicked.parents().hasClass("top-menu"))
    if ($clicked.parents().hasClass("menu_product") 
        || $clicked.parents().hasClass("menu_home")
        || $clicked.hasClass("menu_home")
        || $clicked.hasClass("menu_Product")
        )
        {
        if($('body').hasClass('product'))
        {
            //if this is the Product Page, set the `Product` Button Active
            setActiveMenu(2);
        }
        else
        {
            //The Home Page
            setActiveMenu(0);
        }
        $(".page-content")
        .hide()
        .empty()
					

						
        $('.products').show();
    }
});


function getCategories()
{
    $.ajax({
        url:'admin/main.php?c=getCategories',
        success:function(r){
            $('#CategoryMenu').html(r);
            //Browse the First  Category on Page Load
            $('#CategoryMenu td:first a').click();
			
        }
    })
}


/*
 * Get the products of a specified Category
 */
function browseCategorie(cid,start)
{
    if (lock) return;
    $.ajax({
        url:'admin/main.php?c=browseCategorie&cid='+cid+'&start='+start,
        success:browseCategorieSuccess,
        error:function(){
            lock=false;
        }
    })
}

var browseCategorieSuccess = function(r)
{
    lock=true;
	
    var p1 = $('.product-slider .img1')
    var p2 = $('.product-slider .img2')
    var p3 = $('.product-slider .img3')
    var p4 = $('.product-slider .img4')
    var p5 = $('.product-slider .img5')
    var p6 = $('.product-slider .img6')
	
    var p = [p1,p2,p3,p4,p5,p6]
	
    /*
     *  21.09.2011
     *  Clear The Images PlaceHolders before putting the new images.
     *  Remove the old images of others gallery
     */
    for(i=0;i<p.length;i++ ){
        p[i].empty();
    }
	
	
	
    var holder = $('#imageHolder')
    holder.html(r)

	
    changeWithDelay(p,0,holder,1800)
	
    var currentGallery = $('#gallery_id').val();
    $('#CategoryMenu .hover').removeClass('active')
    $('#CategoryMenu a#'+currentGallery).parent().addClass('active')
    var bgcolor = $('#CategoryMenu a#'+currentGallery).attr('rel');
    $('body').attr('style','background-color:'+bgcolor)

	
	
	
	
}

function changeWithDelay(p,i,holder,delay)
{
    if(i>=p.length)
    {
        //here is the callback of the `changeWithDelay` function
        //when all images load.
		
        var cid = $('#gallery_id').val();
		
        $('.img_item a:not(.unavailable) .full_img').each(function(){
            var href = $(this).attr('src');
            $(this).parent().attr('href',href)
            $(this).parent().attr('rel',cid);
        })
        $('a[rel="'+cid+'"]').colorbox({
            current:''
        });

		
        lock =false;
        return;
    }
    else
    {	
        //p[i] : Image Place Holder (ex: <td class="img1" >..</td>)
        if(exist($('.img'+(i+1)+' img',holder)))
        {//if there an image
			
            //The Basic structure of the p[i]
            var htmlTemplate =
            '<div class="img_item">\
            <div class="img_desc">\
            <span class="img_title"></span>\
            <span class="img_info"></span>\
            </div>\
            <a><img width="244" />\
            <img class="full_img"/>\
            </a>\
            </div>\
            <div class="loader">\
            <img src="admin/image/loader.gif" align="middle"/>\
            </div>'
			
            //Reset the Image Place Holder 
            p[i].empty();
            p[i].addClass('loading')
            .append(htmlTemplate)
			
//            var t = setTimeout(
//                function(){
//                    changeImgContent(p,holder,i);
//                    $('.img_item',p[i]).fadeTo('slow',1);
//                    p[i].removeClass('loading');
//                    changeWithDelay(p,i+1,holder,delay)
//                }
//                ,delay)




$('.img_title',p[i]).html($('.img'+(i+1),holder).attr('title'))
    $('.img_info',p[i]).html($('.img'+(i+1)+' img',holder).attr('alt'))
    
    //set the thumbnail
    $('.img_item a img',p[i]).load(function(){
        p[i].removeClass('loading');
    })
    .attr('src',$('.img'+(i+1)+' .thumb_img',holder).attr('src'));
    
    //set the image
    $('.img_item .full_img',p[i]).attr('src',$('.img'+(i+1)+' .full_img',holder).attr('src'));
		
    //The Attribute `href` and `rel` for the `a` will be putted in the callback Section of the `changeWithDelay`
    //function to prevent the user to click on image before the `colorbox` function be called
    //in case of that the image dosent open in the image will open in a new tab window instead of openning in 
    //the colorbox
				
   

changeWithDelay(p,i+1,holder,delay)



        }
        else
        {	//The current place holder (td) havent a corresponding image in the imagePlaceHolder
            var t = setTimeout(function(){
                $('.img_item',p[i]).fadeTo('slow',0.1);
				
                //Remove the attribute and add the `unavailable` class to disable the link on this image
                $('a',p[i])
                .removeAttr('href')
                .removeAttr('rel')
                .removeAttr('class')
                .addClass('unavailable');
                changeWithDelay(p,i+1,holder,delay)
            },300)
			
        }
    }
}

function changeImgContent(place,holder,i)
{
    $('.img_title',place[i]).html($('.img'+(i+1),holder).attr('title'))
    $('.img_info',place[i]).html($('.img'+(i+1)+' img',holder).attr('alt'))
    
    //set the thumbnail
    $('.img_item a img',place[i]).attr('src',$('.img'+(i+1)+' .thumb_img',holder).attr('src'));
    
    //set the image
    $('.img_item .full_img',place[i]).attr('src',$('.img'+(i+1)+' .full_img',holder).attr('src'));
		
    //The Attribute `href` and `rel` for the `a` will be putted in the callback Section of the `changeWithDelay`
    //function to prevent the user to click on image before the `colorbox` function be called
    //in case of that the image dosent open in the image will open in a new tab window instead of openning in 
    //the colorbox
				
    place[i].removeClass('loading');
		
		
}


function disableNext(option)
{
    if(option==1)
        $('.product-slider .nxtback').addClass('disabled');
    else
        $('.product-slider .nxtback').removeClass('disabled');
}
function disablePrev(option)
{
    if(option==1) 
        $('.product-slider .prvback').addClass('disabled');
    else
        $('.product-slider .prvback').removeClass('disabled');
}

function setCategoryInfo(title1,title2,iconUrl)
{
    $('#category_info .title1').fadeOut('fast',function(){
        $('#category_info .title1').html(title1).fadeIn();
    })
    $('#category_info .title2').html(title2);
    $('#category_info .category_icon img')
    .attr('src',iconUrl)
    .attr('alt',title1)
    .attr('title',title1)
	
}

function subscribe()
{
    var email = $('#email');
    var response='';
    if(!validateEmail(email.val()))
    {
        alert('Please enter a valid email');
        email.focus()
        email.effect("highlight", {
            color:'#e18533'
        }, 3000);
        return;
    }
	
	
    $.ajax({
        url:'admin/main.php?c=subscribe&email='+email.val(),
        success:function(r){
            $('body').append(r);
            $('#email').val('')
        }
		
    })
	
}


function sendEmail(sender)
{
    if($(sender).hasClass('disabled')) return;
	
    var from = $.trim($('#from').val());
    var fname = $.trim($('#fname').val());
    var lname = $.trim($('#lname').val());
    var phone = $.trim($('#phone').val());
    var comment= $.trim($('#comment').val());
    var required = false;
	
    if(!validateEmail($('#from').val()))
    {
        var f = $('#from');
        var old = f.val();
        f.val('Invalid Email');
        $('#from').effect("highlight", {
            color:'#e18533'
        }, 1000,function(){
            f.val(old);
            f.focus()
        });
        return false;
    }
	
	
	
    $('.page-content .required').each(function(){
		
        if($.trim($(this).val())=='')
        {
            $(this).effect("highlight", {
                color:'#e18533'
            }, 1000);
            required =true;
        }
	
    })
		
    if(!required){
	
        $(sender).addClass('disabled');	
	
        $.ajax({
            url:'admin/main.php?c=sendemail&from='+from+'&fname='+fname+'&lname='+lname+'&phone='+phone+'&comment='+comment,
            success:function(r){
                $('body').append(r);
                $(sender).removeClass('disabled')
            }
		
        })
	
    }
	
}

function resetForm()
{
    $('.page-content input[type="text"],.page-content textarea').val('')
}



