var paper;
var stem_color = '#C1D72E';
var base_dir = '/wordpress/wp-content/themes/coachconner/js-sidebar/';
var base_ajaxForAll = 'http://www.coachconner.com/category/main/#url=http%3A//www.coachconner.com/'
var selected_node = null;
var left_side_load_complete = false;
var vines = {
    1: [
        'M200 400 ',
        'v -100 ',
        'c0,-6.5 -6.5,-13 -13,-13 ',
        'h -35 ',
        'c-6.5,0 -13,-6.5 -13,-13 ',
        'v -65 ',
       ],
    2: [
        'M138 236',
        'h35 ',
        'c6.5,0 13,-6.5 13,-13 ',
        'v-95',
       ],
    3: [
        'M200 320',
        'h60 ',
        'c6.5,0 13,-6.5 13,-13 ',
        'v-55',
       ],
    4: [
        'M273 303',
        'h-20 ',
        'c-6.5,0 -13,-6.5 -13,-13 ',
        'v-100',
       ],
	5: [
        'M0 530',
        'h40',
        'c10 0 30 -5 30 -20',
        'v-80',
        'V200',
       ],
	6: [
        'M0 580',
        'h100',
        'c10 0 30 -5 30 -20',
        'v-270',
        'V200',
       ],
	7: [
        'M0 555',
        'h160',
        'c10 0 30 -5 30 -20',
        'v-150',
        'V200',
       ],
};

var leaves = {
    1:  {x: 200, y: 350, size: .5, },
    2:  {x: 200, y: 340, size: .5, },
    3:  {x: 240, y: 280, size: .5, },
    4:  {x: 240, y: 290, size: .5, },
    5:  {x: 138, y: 270, size: .8, },
    6:  {x: 138, y: 260, size: .8, },
    7:  {x: 186, y: 200, size: .8, },
    8:  {x: 186, y: 220, size: .8, },
    9:  {x:  70, y: 500, size: .8, },
    10: {x: 130, y: 410, size: .8, },
    11: {x: 190, y: 450, size: .8, },
};

var flowers = {
    1: {x: 135, y: 205, w:40, h:40, offset: -20, name: base_dir + 'flower2_small.svg', r: 0 },
    2: {x: 185, y: 120, w:40, h:40, offset: -20, name: base_dir + 'flower3_small.svg', r: 0 },
    3: {x: 275, y: 250, w:40, h:40, offset: -20, name: base_dir + 'flower3_small.svg', r: 0 },
    4: {x: 240, y: 188, w:50, h:50, offset: -25, name: base_dir + 'flower1_small.svg', r: 0 },
    5: {x: 70,  y: 430, w:60, h:60, offset: -30, name: base_dir + 'flower3_big.svg',   r: 0 },
    6: {x: 130, y: 315, w:60, h:60, offset: -30, name: base_dir + 'flower2_big.svg',   r: 0 },
    7: {x: 190, y: 380, w:60, h:60, offset: -30, name: base_dir + 'flower2_big.svg',   r: 0 },
};

var texts = {
    1:  {text_name: base_dir + 'home_energy.svg',    w: 67, h:28, x: flowers[1]['x'] - 110, y: flowers[1]['y'] - 20},
    2:  {text_name: base_dir + 'home_mind.svg',      w: 56, h:21, x: flowers[2]['x'] - 100, y: flowers[2]['y']},
    3:  {text_name: base_dir + 'home_about.svg',     w: 42, h:14, x: flowers[3]['x'] + 40,  y: flowers[3]['y']},
    4:  {text_name: base_dir + 'home_body.svg',      w: 81, h:50, x: flowers[4]['x'] + 40,  y: flowers[4]['y'] - 30}, 
    5:  {text_name: base_dir + 'home_resources.svg', w: 83, h:13, x: 220,                   y: 350}, 
    6:  {text_name: base_dir + 'home_contact.svg',   w: 66, h:14, x: 110,                   y: 350}, 
    7:  {text_name: base_dir + 'home_mind.svg',      w: 56, h:21, x: flowers[5]['x'] - 30,  y: flowers[5]['y'] - 60}, 
    8:  {text_name: base_dir + 'home_energy.svg',    w: 67, h:28, x: flowers[6]['x'] - 30,  y: flowers[6]['y'] - 60}, 
    9:  {text_name: base_dir + 'home_body.svg',      w: 81, h:50, x: flowers[7]['x'] - 40,  y: flowers[7]['y'] - 90}, 
    10: {text_name: base_dir + 'home_about.svg',     w: 42, h:14, x: 5,                     y: 510}, 
    11: {text_name: base_dir + 'home_contact.svg',   w: 66, h:14, x: 5,                     y: 560}, 
    12: {text_name: base_dir + 'home_resources.svg', w: 83, h:13, x: 5,                     y: 535}, 
};

var hit_areas = {
    1:  {x: flowers[1]['x'] - 120,  y: flowers[1]['y'] - 40, width: 140, height: 70,  area: 'energy',    url:'/category/energy'},      //home
    2:  {x: flowers[2]['x'] - 100,  y: flowers[2]['y'] - 30, width: 130, height: 60,  area: 'mind',      url:'/category/mind'},
    3:  {x: flowers[3]['x'] - 30,    y: flowers[3]['y'] - 30, width: 120, height: 55,  area: 'about',     url:'/about'},
    4:  {x: flowers[4]['x'] - 30,    y: flowers[4]['y'] - 30, width: 160, height: 60,  area: 'body',      url:'/category/body-balance'},
    5:  {x: texts[5]['x'] - 5,           y: texts[5]['y'] - 5,    width: 90,  height: 20,  area: 'resources', url:'/category/products'},
    6:  {x: texts[6]['x'] - 5,           y: texts[6]['y'] - 5,    width: 75,  height: 20,  area: 'contact',   url:'/contact'},
    7:  {x: texts[7]['x'] - 5,           y: texts[7]['y'] - 5,    width: 75,  height: 100, area: 'mind',   flower: 5, vine: 5},      //left side
    8:  {x: texts[8]['x'] - 5,           y: texts[8]['y'] - 5,    width: 80,  height: 100, area: 'energy', flower: 6, vine: 6},
    9:  {x: texts[9]['x'] - 5,           y: texts[9]['y'] - 5,    width: 90,  height: 140, area: 'body',   flower: 7, vine: 7},
    10: {x: texts[10]['x'] - 5,        y: texts[10]['y'] - 5,   width: 50,  height: 20,  area: 'about'},
    11: {x: texts[11]['x'] - 5,       y: texts[11]['y'] - 5,   width: 75,  height: 20,  area: 'contact'},
    12: {x: texts[12]['x'] - 5,       y: texts[12]['y'] - 5,   width: 90,  height: 20,  area: 'resources'},
};

function init()
{
    if ($('body').hasClass('home')) {
        initHome();
    } else {
        initLeftSideMenu();
    }
}

function initHome()
{
    paper = Raphael(document.getElementById('canvas'), 800, 800);
    paper.image('/wordpress/wp-content/themes/coachconner/js-sidebar/puddle.svg', 100, 388, 200, 25);
    var cloud = paper.image('/wordpress/wp-content/themes/coachconner/js-sidebar/cloud.png', 0, 0, 270, 95);
    cloud.animate({x: 70}, 750, 'backOut', function() {
                                            createDrop(120, 50);
                                            setTimeout(function() { createDrop(270, 90); }, 100);
                                            setTimeout(function() { createDrop(200, 90); }, 200);
                                            setTimeout(function() { createDrop(170, 90); }, 300);
                                       });
    
    //Draw the main vine that everything else springs from
    var animated_path = initVinePaths(1);
    var vine = paper.path(vines[1][0]);  //"Move" part of path
    vine.attr({'stroke-width': 2, stroke: stem_color});
    vine.animate({
        '30%': {path: animated_path[1], callback: function() { 
                                                        createLeaf(1, -25, -65); 
                                                        createLeaf(2,  25,  80);
                                                        drawVine3();
                                                      } },
        '40%':  {path: animated_path[2]},
        '60%':  {path: animated_path[3]},
        '70%':  {path: animated_path[4]},
        '100%': {path: animated_path[5], callback: function() {
                                                        createLeaf(5, -25, -65);
                                                        createLeaf(6,  25,  80);
                                                        createFlower(1);
                                                        drawVine2();
                                                      } }
    }, 600);
}

function initVinePaths(which)
{
    var v_paths = vines[which];
    var path_str;
    var animated = {};
    
    //Initial "move" part of the path
    path_str = v_paths[0]; 
    for(var i = 1; i < v_paths.length; i++) {
        path_str += v_paths[i];  //Next segment of vine
        animated[i] = path_str;
    }
    return animated;
}

function drawVine2()
{
    var animated_path = initVinePaths(2);
    var vine = paper.path(vines[2][0]);  //"Move" part of path
    vine.attr({'stroke-width': 2, stroke: stem_color});
    vine.animate({
        '40%':  {path: animated_path[1]},
        '60%':  {path: animated_path[2]},
        '100%': {path: animated_path[3], callback: function() {
                                                        createLeaf(7, -25, -80);
                                                        createLeaf(8,  25,  65);
                                                        createFlower(2);
                                                      } }
    }, 400);
}

function drawVine3()
{
    var animated_path = initVinePaths(3);
    var vine = paper.path(vines[3][0]);  //"Move" part of path
    vine.attr({'stroke-width': 2, stroke: stem_color});
    vine.animate({
        '40%':  {path: animated_path[1]},
        '60%':  {path: animated_path[2], callback: function() {
                                                        drawVine4();
                                            }},
        '100%': {path: animated_path[3], callback: function() {
                                                        createFlower(3);
                                                      } }
    }, 500);
}

function drawVine4()
{
    var animated_path = initVinePaths(4);
    var vine = paper.path(vines[4][0]);  //"Move" part of path
    vine.attr({'stroke-width': 2, stroke: stem_color});
    vine.animate({
        '40%':  {path: animated_path[1]},
        '60%':  {path: animated_path[2]},
        '100%': {path: animated_path[3], callback: function() {
                                                        createLeaf(3,  25,  80); 
                                                        createLeaf(4, -25, -65);
                                                        createFlower(4);
                                                        
                                                        //Now that we are finished
                                                        setTimeout(function() { createText(1); createHomeHitArea(1); }, 100);
                                                        setTimeout(function() { createText(2); createHomeHitArea(2); }, 200);
                                                        setTimeout(function() { createText(4); createHomeHitArea(3); }, 300);
                                                        setTimeout(function() { createText(3); createHomeHitArea(4); }, 400);
                                                        setTimeout(function() { createText(5); createHomeHitArea(5); }, 500);
                                                        setTimeout(function() { createText(6); createHomeHitArea(6); }, 600);
                                                      } }
    }, 400);
}

function createLeaf(which, init_angle, final_angle)
{
    var config = leaves[which];
    var leaf = paper.path('M' + config['x'] + ' ' + config['y'] + 
                          'l-10 -20' +
                          'c-5 -17 25 -17 20 0' +
                          'l-10 20');
    leaf.attr({stroke: 'none', 
               fill: stem_color, 
               rotation: init_angle+' '+config['x']+' '+config['y'],
               scale: config['size']+' '+config['size']+' '+config['x']+' '+config['y']});
    leaf.animate({rotation: final_angle+' '+config['x']+' '+config['y']}, 2000, 'elastic');
}

function createDrop(x, y)
{
    var path_str = 'M' + x + ' ' + y +
                   'l 2.5 5' +
                   'c 1.25 4.25 -6.25 4.25 -5 0' +
                   'l 2.5 -5';
    var drop = paper.path(path_str);
    drop.attr({stroke: 'none', fill: '#99dceb'});
    drop.animate({translation: '0 400', opacity: 0}, 500, function() {this.remove();} );
}

function createFlower(which, offset)
{
    var config = flowers[which];
    var flower = paper.image(config['name'],
                             config['x'] + config['offset'], 
                             config['y'] + config['offset'], 
                             config['w'], 
                             config['h']);
    flowers[which]['flower_node'] = flower;
}

function createHomeHitArea(which)
{
    var config = hit_areas[which];
    var hit_area = paper.rect(config['x'], 
                              config['y'], 
                              config['width'], 
                              config['height']);
    hit_area.attr({fill: '#ffffff', opacity: 0, cursor: 'pointer'});
    hit_areas[which]['hit_node'] = hit_area;
    
    if (which <= 4) {
        hit_area.mouseover(function() {
            var config = flowers[which];
            var flower = config['flower_node'];
            var rot = flower.attr('rotation');
            if (rot !== 0) {
                rot = parseInt(rot.split(' ')[0]);
                rot = rot % 360;
                flower.attr({rotation: rot + ' ' + config['x'] + ' ' + config['y']});
            }
            rot += 360;
            flower.stop();
            flower.animate({rotation: rot + ' ' + config['x'] + ' ' + config['y']}, 1500, '>');
        });
    }
    
    hit_area.click(function() {
        location.href = hit_areas[which]['url'];
    });
    
    if (which == 6) {
        for(var i = 1; i <= 6; i++) {
            hit_area = hit_areas[i]['hit_node'].toFront();
        }
    }
    
}

function createLeftSideHitArea(which)
{
    var config = hit_areas[which];
    var hit_area = paper.rect(config['x'], 
                              config['y'], 
                              config['width'], 
                              config['height']);
    hit_area.attr({fill: '#ffffff', opacity: 0, cursor: 'pointer'});
    hit_areas[which]['hit_node'] = hit_area;
    
    hit_area.click(function() {
        chooseArea(which);
    });
    
    //Move the hit areas to the front once they are all rendered
    if (which == 12) {
        for(var i = 7; i <= 12; i++) {
            hit_area = hit_areas[i]['hit_node'].toFront();
        }
    }
}

function createText(which, offset)
{
    var config = texts[which];
    text = paper.image(config['text_name'], 
                       config['x'], 
                       config['y'], 
                       config['w'], 
                       config['h']);
    text.attr({opacity: 0});
    text.animate({opacity: 1}, 1000, '>');
    
    texts[which]['text_node'] = text;
}

function initLeftSideMenu()
{
    paper = Raphael(document.getElementById('canvas'), 300, 600);
    //paper.setSize(300, 800);
    //$(paper.canvas).show();
    //paper = Raphael(document.getElementById('canvas'), 300, 600);
    
    cloud = paper.image('/wordpress/wp-content/themes/coachconner/js-sidebar/cloud.png', -500, 10, 270, 95);
    cloud.animate({x: 20}, 500, '>');
    
	createLeftVine(5);
	createLeftVine(6);
	createLeftVine(7);
    
}

function createLeftVine(which)
{
	var animated = initVinePaths(which);
	
	var vine = paper.path(vines[which][0]);
    var leaf = leaves[which];
    var flower = flowers[which];
    
    //vines[which] = vine;
	var random_rot = Math.floor(Math.random() * 21) - 10; //Random rotation from 0 to 10
	vine.attr({'stroke-width': 3, stroke: stem_color});
    vines[which]['vine_node'] = vine;
    
    var last_step_callback = function() {
                                createLeaf(which + 4, 0, -60 - random_rot); 
                                createLeaf(which + 4, 0, 60 - random_rot); 
                                createFlower(which);
                                createText(which + 2);  //Text associated with this flower
                                createLeftSideHitArea(which + 2);
                                createText(which + 5);  //Extra text that shows up at the bottom
                                createLeftSideHitArea(which + 5);
                                leftSideLoadComplete();
                            };

	vine.animate({
		"33%"  : {path: animated[1]},
		"66%"  : {path: animated[2]},
		"100%" : {path: animated[3], callback: last_step_callback},
	}, 500);
}

function chooseArea(hit_idx, load_body)
{
    if (selected_node == hit_idx) {
        return false;
    }
    var flower, hit_area;
    var vine_idx;
    //if load_body wasn't called in the function, default it to true
    load_body = typeof(load_body) != 'undefined' ? load_body : true;
    
    if (selected_node !== null && selected_node <= 9 && selected_node >= 7) {
        hit_area = hit_areas[selected_node];
        vine_idx = hit_area['vine'];
        flower = flowers[hit_area['flower']];
        
        vine_paths = initVinePaths(vine_idx);
        
        hit_area['hit_node'].animate({y: hit_area['y']}, 250, '>');
        flower['flower_node'].animate({y: flower['y'] + flower['offset']}, 250, '>');
        vines[vine_idx]['vine_node'].animate({path: vine_paths[3]}, 250, '>');
        texts[selected_node]['text_node'].animate({y: texts[selected_node]['y']}, 250, '>');
    }
    
    if (hit_idx <= 9 && hit_idx >= 7) {
        hit_area = hit_areas[hit_idx];
        vine_idx = hit_area['vine'];
        flower = flowers[hit_area['flower']];
        
        var offset = 200 - flower['y'];
        vine_paths = initVinePaths(vine_idx);
        hit_area['hit_node'].animate({y: hit_area['y'] + offset}, 250, '>');
        flower['flower_node'].animate({y: flower['y'] + flower['offset'] + offset}, 250, '>');
        texts[hit_idx]['text_node'].animate({y: texts[hit_idx]['y'] + offset}, 250, '>');
        vines[vine_idx]['vine_node'].animate({path:vine_paths[4] }, 250, '>');
    }
    
    selected_node = hit_idx;
    if (load_body) {
        loadBodyContent(hit_areas[hit_idx]['area']);
    }
}

function loadBodyContent(type)
{
    var content_url;
    switch(type) {
        case 'mind':
            content_url = 'http%3A//www.coachconner.com/category/mind/';
            break;
        case 'energy':
            content_url = 'http%3A//www.coachconner.com/category/energy/'
            break;
        case 'body':
            content_url = 'http%3A//www.coachconner.com/category/body-balance/'
            break;
        case 'about':
            content_url = 'http%3A//www.coachconner.com/about/'
            break;
        case 'resources':
            content_url = 'http%3A//www.coachconner.com/category/products/'
            break;
        case 'contact':
            content_url = 'http%3A//www.coachconner.com/contact/'
            break;
        default:
            break;
    }
    
    var href = location.href;

    if (href.search('url=') != -1) {
       href = href.replace(/url=.*/, 'url='+content_url);
    } else {
        href += '#url=' + content_url;
    }
    location.href= href;
    //Execute the 'ajax-for-all' function that swaps out the body content
    //dispatcher.fire(content_url);
    
    /*
    This may be useful later, but for now just reload the page
    $.ajax({
        url: content_url,
        success: function(data) {
            $('#right_content').html(data);
        }
    });
    */
}

function leftSideLoadComplete()
{
    //I can't think of a good way to have this activate, so I'll just check
    // that it doesn't get started until the data is loaded and do it only once
    if (left_side_load_complete == false && hit_areas[7].hit_node && hit_areas[8].hit_node && hit_areas[9].hit_node) {
        if (location.pathname.search('body-balance') != -1) {
            chooseArea(9, false);
        } else if (location.pathname.search('mind') != -1) {
            chooseArea(7, false);
        } else if (location.pathname.search('energy') != -1) {
            chooseArea(8, false);
        }
        left_side_load_complete = true;
    }
}

function drawX(x, y)
{
    paper.path('M'+ x + ' ' + y + 'm0 -10 l0 20 m-10 -10 l20 0');
}

